Lucia
Lucia

Reputation: 203

How to send Newsletters (bulk emails) asynchronously in ASP.NET

I need to send about 5000 emails as newsletter to my website users asynchronously.. The problem is i don't know the best way to send them asynchronously ..Please help me updating my code to make it asynchronously

My Code:

   public string SendEmail()
    {


        foreach (var emailAddress in EmailList)

        {
            var message = new MailMessage("[email protected]", emailAddress);

            message.Subject = "hi";
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.Credentials = new NetworkCredential("[email protected]", "*****");
            client.EnableSsl = true;
            client.Send(message);
        }
        return "done";
    }

Thank you , Lucy

Upvotes: 1

Views: 1654

Answers (2)

Eli Y
Eli Y

Reputation: 907

edit: if it's being used inside of action you should mark your action async

public async Task<ActionResult> MyAction()

for a start, don't create SmtpClient for every message so as follows and also this, should send the mails asynchronously but wait for all of them to be sent

    public string SendEmail()
    {
        var tasks = new List<Task>();
        var client = new SmtpClient("smtp.gmail.com", 587);
        client.Credentials = new NetworkCredential("[email protected]", "*****");
        client.EnableSsl = true;
        foreach (var emailAddress in EmailList)
        {
            var message = new MailMessage("[email protected]", emailAddress);
            message.Subject = "hi";
            tasks.Add(client.SendMailAsync(message));
        }
        while(tasks.Count > 0)
        {
            var idx = Task.WaitAny(tasks.ToArray());
            tasks.RemoveAt(idx);
        }
        return "done";
    }

Upvotes: 0

DVK
DVK

Reputation: 2792

Take a look at the async and await keywords.

https://msdn.microsoft.com/en-us/library/mt674882.aspx

The async and await keywords in C# are the heart of async programming. By using those two keywords, you can use resources in the .NET Framework or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. Asynchronous methods that you define by using async and await are referred to as async methods.

MSDN explains the syntax side of things. The bigger concern is error handling and reliably. Dumping 5,000 emails into a list and hitting the "send" button on them is a little optimistic. Do these emails need to be reliably delivered? What happens if 3,000 of them send, and a network error suddenly causes temporary connectivity loss to the outgoing mail server? Are you going to resend all 5,000 when it starts working again? Just forget about the last 2,000? Are the recipients going to be mad because they got duplicates, or didn't get the message at all? How are you going to troubleshoot errors?

A pattern that I've found that has worked really well (whether you are sending synchronously or asynchronously), is to generate the messages and store each in a database table, and then use something like the following:

public void SendAllEmails()
{
    var emails = SomeClass.GetAllUnsentEmails();

    foreach(Email message in Emails)
    {
        var success = SendEmail(message);

        if (!success)
        {
            // Do you want to do something if it fails?
        }
    }
}

public bool SendEmail(Email message)
{
    try
    {
        // 1. Send the email message
        // 2. Update the "SentOn" date in the database
        // 3. return true
    }
    catch(Exception ex)
    {
        SomeClass.CreateEmailErrorEntry(message, ex); // store error in a table or log
        return false;
    }
}

Upvotes: 2

Related Questions