SmtpClient を作成するクラスを作成し、電子メールを送信する (同期) 電子メール コードがいくつかあります。SmtpClient は再利用されません。ただし、時々次の例外が発生します。
System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.InvalidOperationException: An asynchronous call is already in progress. It must be completed or canceled before you can call this method.
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at EmailSender.SendMail(MailAddress fromMailAddress, string to, String subject, String body, Boolean highPriority) in ...\EmailSender.cs:line 143
コードは次のようになります。
// ...
var emailSender = new EmailSender();
emailSender.SendMail(toEmail, subject, body, true);
// emailSender not used past this point
// ...
public class EmailSender : IEmailSender
{
private readonly SmtpClient smtp;
public EmailSender()
{
smtp = new SmtpClient();
}
public void SendMail(MailAddress fromMailAddress, string to, string subject, string body, bool highPriority)
{
if (fromMailAddress == null)
throw new Exception();
if (to == null)
throw new ArgumentException("No valid recipients were supplied.", "to");
// Mail initialization
var mailMsg = new MailMessage
{
From = fromMailAddress,
Subject = subject,
Body = body,
IsBodyHtml = true,
Priority = (highPriority) ? MailPriority.High : MailPriority.Normal
};
mailMsg.To.Add(to);
smtp.Send(mailMsg);
}
}