我在发送电子邮件列表时使用 SmtpClient 的 SendCompletedEventHandler。
SendCompletedEventHandler 仅在已发送列表中的所有电子邮件时调用。
我解释说,发送电子邮件时会调用 SendCompletedEventHandler。
我的代码有问题吗?
public void SendAllNewsletters(List<string> recipients)
{
string mailText = "My Text";
foreach(string recipient in recipients)
{
//if this loop takes 10min then the first call to
//SendCompletedCallback is after 10min
SendNewsletter(mailText,recipient);
}
}
public bool SendNewsletter(string mailText , string emailaddress)
{
SmtpClient sc = new SmtpClient(_smtpServer, _smtpPort);
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(_smtpuser, _smtppassword);
sc.Credentials = SMTPUserInfo;
sc.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
MailMessage mm = null;
mm = new MailMessage(_senderemail, emailaddress );
mm.IsBodyHtml = true;
mm.Priority = MailPriority.Normal;
mm.Subject = "Something";
mm.Body = mailText ;
mm.SubjectEncoding = Encoding.UTF8;
mm.BodyEncoding = Encoding.UTF8;
//Mail
string userState = emailaddress;
sc.SendAsync(mm, userState);
return true;
}
public void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string)e.UserState;
if (e.Error != null)
{
_news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, false, e.Error.Message);
}
else
{
_news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, true, string.Empty);
}
}
最佳答案
您每次都在创建一个新的 SmtpClient
实例(然后重新分配处理程序)。使用范围更大的静态变量。
关于c# - 使用 SmtpClient 发送邮件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2684415/