1

我想修改此方法以允许将邮件发送给多个用户,而不是一个一个地发送。

我使用以下方法通过根据用户数量将方法循环发送给大量用户,但需要几分钟才能让用户感觉发生了错误..

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;
            }
        }

是否有某种方法可以重构此方法以允许将邮件发送给多个用户。

4

1 回答 1

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;
            }
        }
于 2013-09-03T11:15:27.330 回答