質問

We use the excellent AuthSMTP service for outgoing mail from our MVC application. Until we upgraded to .Net 4.5.1 we used SmtpMail.SendAsync to send out multiple emails at once via IIS7. IIS7 is set to relay mail through AuthSMTP.

These days asynchronous code in .Net seems to work differently. We rolled back to SmtpMail.Send which has slowed the site down where multiple mails are sent. We are considering the following options.

  1. Rewrite the code to work with the Task-based Asynchronous Pattern. We're fairly confused by this but could persevere if it's a good option.

  2. Save email to the database and send it using a console application triggered as a scheduled task. We like this option because it gives us an archive of sent email. On the other hand we'd need to hit the database to store the emails, which may be slower than asking IIS to dump outgoing mail to a queue folder.

  3. Have IIS save outgoing mail to a queue folder, and write a console application to process that queue. We could archive each message on disk, which is a worse archiving solution than storing in database.

  4. Something else.

Can anyone tell us the most performant solution base on their experience?

Thanks!

役に立ちましたか?

解決

Call your email function in a separate thread, that will send emails in background Try this code.

public static void SendEmail(string from, string[] to, string[] CC, string[] BCC, string subject, string body, SMTPSettings _smtp = null)
{
    Thread email = new Thread(delegate()
    {
        SendAsyncEmail(from, to, CC, BCC, subject, body, _smtp);
    });
    email.IsBackground = true;
    email.Start();
}

private static void SendAsyncEmail(string from, string[] to, string[] CC, string[] BCC, string subject, string body, SMTPSettings _smtp = null)
{
    try
    {
        MailMessage message = new MailMessage();
        SmtpClient client = new SmtpClient();       
        if (_smtp != null)
        {
            client.Host = _smtp.SMTPServer;
            client.Port = Convert.ToInt32(_smtp.SMTPPort);
            client.EnableSsl = _smtp.SMTPEnableSSL;
            client.Credentials = new System.Net.NetworkCredential(_smtp.SMTPUserEmail, SMTPPassword);
        }

        message.From = new MailAddress(from);
        message.Subject = subject;
        message.Body = body;
        message.IsBodyHtml = true;
        foreach (string t in to)
        {
            message.To.Add(new MailAddress(t));
        }

        if (CC != null)
            foreach (string c in CC)
            {
                message.CC.Add(new MailAddress(c));
            }

        if (BCC != null)
            foreach (string b in BCC)
            {
                message.Bcc.Add(new MailAddress(b));
            }
        client.Send(message);
    }
    catch (Exception ex)
    {
        ErrorLogRepository.LogErrorToDatabase(ex, null, null, "");
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top