Asynchronously sending Emails in C#?

Viewed 61238

I'm developing an application where a user clicks/presses enter on a certain button in a window, the application does some checks and determines whether to send out a couple of emails or not, then show another window with a message.

My issue is, sending out the 2 emails slows the process noticeably, and for some (~8) seconds the first window looks frozen while it's doing the sending.

Is there any way I can have these emails sent on the background and display the next window right away?

Please don't limit your answer with "use X class" or "just use X method" as I am not all too familiarized with the language yet and some more information would be highly appreciated.

Thanks.

11 Answers

i think this is the best way :

public async Task Send(string to, string subject, string body)
    {
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.mail.yahoo.com");
        mail.From = new MailAddress("yourEmail@email.com", "sender name");
        mail.To.Add(to);
        mail.Subject = subject;
        mail.Body = body;
        mail.IsBodyHtml = true;
        SmtpServer.Port = 587;
        SmtpServer.Credentials = new System.Net.NetworkCredential("yourEmail@email.com", "your key");
        SmtpServer.EnableSsl = true;

       await Task.Run(() =>
       {
           SmtpServer.SendAsync(mail, null);
       });
    }
Related