我想修改此方法以允许向多个用户发送邮件而不是逐个发送邮件。
我使用以下方法通过根据用户数量将方法放入循环中来向大量用户发送邮件,但这需要几分钟时间让用户感觉发生了错误。
public static string sendMail(string to, string title, string subject, string body)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
if (to == "")
to = "----@gmail.com";
MailAddressCollection m = new MailAddressCollection();
m.Add(to);
mail.Subject = subject;
mail.From = new MailAddress( "----@gmail");
mail.Body = body;
mail.IsBodyHtml = true;
mail.ReplyTo = new MailAddress("----@gmail");
mail.To.Add(m[0]);
smtp.Host = "smtp.gmail.com";
client.Port = 25;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("----@gmail", "####");
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtp.Send(mail);
return "done";
}
catch (Exception ex)
{
return ex.Message;
}
}
是否有某种方法可以重构此方法以允许将邮件发送给多个用户。
答案 0 :(得分:4)
public static string sendMail(string[] tolist, string title, string subject, string body)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
if (to == "")
to = "----@gmail.com";
MailAddressCollection m = new MailAddressCollection();
//Add this
foreach(string to in tolist)
{
m.Add(to);
}
//
mail.Subject = subject;
mail.From = new MailAddress( "----@gmail");
mail.Body = body;
mail.IsBodyHtml = true;
mail.ReplyTo = new MailAddress("----@gmail");
//And Add this
foreach(MailAddress ma in m)
{
mail.To.Add(ma);
}
//or maybe just mail.To=m;
smtp.Host = "smtp.gmail.com";
client.Port = 25;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("----@gmail", "####");
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtp.Send(mail);
return "done";
}
catch (Exception ex)
{
return ex.Message;
}
}