James
James

Reputation: 2246

Sending mails asynchronously

I have method as below to send email, when ever any error occurs in our application. [Yes. sending errors through mails is a separate discussion]

public void EmailErrorDetails()
{
    string strBodyMessage = string.Empty;
    strBodyMessage = GetEmailBodyMessage();

    if (strBodyMessage != String.Empty)
    {
        MailMessage emailMessage = new MailMessage();
        emailMessage.From = new MailAddress(Constants.MailFrom);
        emailMessage.To.Add(Constants.MailTo);
        emailMessage.Subject = Constants.EmailSubject;
        emailMessage.IsBodyHtml = true;
        emailMessage.Body = string.Format(strBodyMessage);

        SmtpClient client = new SmtpClient();
        client.UseDefaultCredentials = false;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.EnableSsl = true;
        client.Host = Constants.EmailHostAddress;
        client.Port = Convert.ToInt32(Constants.EmailPort);
        client.Credentials = new NetworkCredential(Constants.MailFrom, Constants.MailFromPassword);
        client.Send(emailMessage);


    }
}

I want to make this method run asynchronously in background, and the execution to move ahead.

I read that [client.Send] itself uses asynchronous calling. So is there any benefit making the above method call asynchronous way, and if yes how can I achieve this?

Upvotes: 0

Views: 107

Answers (1)

James
James

Reputation: 82096

I read that client.Send uses asynchronous calling

Assuming client is actually an SmtpClient, then Send does not use asynchronous calling. SmtpClient has a specific method for sending emails asynchronously and it's called SendAsync - if you want to send an email in the background, use this instead of Send.

Upvotes: 1

Related Questions