Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Send Mail Async

Tags:

c#

.net

identity

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?

like image 311
Ammar Khan Avatar asked May 18 '14 19:05

Ammar Khan


1 Answers

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);
        }
    }
}
like image 168
MarcinJuraszek Avatar answered Nov 14 '22 18:11

MarcinJuraszek