sayana
sayana

Reputation: 69

Sending bulk emails in c # .net windows application

My project is to send at least 100 mails an hour.

I have used for loop to retrieve emails from database and send email one by one.

But When I googled i find out that it will get time out after some time.So What is the method to use to hold the mail sending for a while and then restart the loop from hold position.Also,if the sending failed i should resend it.Should I use timer?

Please provide me any idea to complete this.

My sample code,

List<string> list = new List<string>();
        String dbValues;
        foreach (DataRow row in globalClass1.dtgrid.Rows)
        {
            //String From DataBase(dbValues)
            dbValues = row["email"].ToString();

            list.Add(dbValues);


        }
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(mailserver, port))
        {
            client.Credentials = new System.Net.NetworkCredential(emailfrom, password);
            client.EnableSsl = true;

            MailMessage msg1 = new MailMessage();
            foreach (string row in list)
            {
                if (row != null)
                {
                    msg1=sendmail(row);
                    client.Send(msg1);
                    client.Dispose();
}
}}

Upvotes: 1

Views: 6276

Answers (2)

Reza Aghaei
Reza Aghaei

Reputation: 125187

Option 1

You can simply Add multiple recipients to To property of MailMessage:

var mail = new MailMessage();   
mail.To.Add(new MailAddress("[email protected]"));

For example when you have a list that contains recipients, you can add theme all:

var mail = new MailMessage();

foreach (var item in list)
{
   mail.To.Add(new MailAddress(item));
}

mail.From = new MailAddress("[email protected]");
mail.Subject = "Subject";
mail.Body = "Body";

client.Send(mail);

Option 2

If you don't want to set all addresses using To or Bcc you can can use a Task to send emails this way:

public void SendMails(List<string> list)
{
    Task.Run(() =>
    {
        foreach (var item in list)
        {
            //Put all send mail codes here 
            //...
            //mail.To.Add(new MailAddress(item));
            //client.Send(mail);
        }
    });
}

Option 3

You can also use SendMailAsync to send mails.

Thanks to Panagiotis Kanavos to mention that this way is preferred instead of using Task.Run .

Upvotes: 2

Matt Evans
Matt Evans

Reputation: 7575

You should rather send them asynchronously using the pickup directory. Here is a good overview. http://weblogs.asp.net/gunnarpeipman/asp-net-using-pickup-directory-for-outgoing-e-mails

The SMTP server handles transient network connectivity issues, and retries periodically.

Upvotes: 0

Related Questions