Reputation: 11403
I want to modify this method to allow sending mail to multiple users instead of one by one .
I use the following method to send mail to bulk of users through putting the method in a loop according to the number of users but it takes several minutes making the user feeling that something wrong has been happened ..
public static string sendMail(string to, string title, string subject, string body)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
if (to == "")
to = "[email protected]";
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;
}
}
Is there some way to refactor this method to allow sending the mail to multiple user .
Upvotes: 1
Views: 2941
Reputation: 8786
public static string sendMail(string[] tolist, string title, string subject, string body)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
if (to == "")
to = "[email protected]";
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;
}
}
Upvotes: 4