Ammar Khan
Ammar Khan

Reputation: 2585

How to Send Mail Async

I am running into an issue when trying to send an Email Async, I found out a no of post on Stackoverflow but none of them was helpful. I have following block of code

public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        // Plug in your email service here to send an email.

        var mailMessage = new MailMessage
            ("[email protected]", message.Destination, message.Subject, message.Body);

        mailMessage.IsBodyHtml = true;

        var client = new SmtpClient();

        client.SendCompleted += (s, e) => client.Dispose();
        client.SendAsync(mailMessage,null);
        return Task.FromResult(0);
    }
}

I got an email but getting an exception when this block of code run

an asynchronous module or handler completed while an asynchronous operation was still pending.

Any suggestion?

Upvotes: 5

Views: 17391

Answers (2)

BillHaggerty
BillHaggerty

Reputation: 6571

-Future readers, dispose the MailMessage, or as I prefer to do use the using syntax! I don't know how much memory you lose when you don't dispose it or if it can somehow be reclaimed. I am going to be sending a lot of emails to users so I don't want to find out if it will stop working over time if left alone.

public class EmailService : IIdentityMessageService
        {
            public async Task SendAsync(IdentityMessage message)
            {
                // Plug in your email service here to send an email.

                using (var mailMessage = new MailMessage("[email protected]", message.Destination, message.Subject, message.Body))
                {
                    mailMessage.IsBodyHtml = true;

                    using (var client = new SmtpClient())
                    {
                        await client.SendMailAsync(mailMessage);
                    }
                }
            }
        }

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Use SendMailAsync instead of SendAsync:

public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        // Plug in your email service here to send an email.

        var mailMessage = new MailMessage
            ("[email protected]", message.Destination, message.Subject, message.Body);

        mailMessage.IsBodyHtml = true;

        using(var client = new SmtpClient())
        {
            await client.SendMailAsync(mailMessage);
        }
    }
}

Upvotes: 18

Related Questions