如何向多个收件人发送电子邮件

时间:2018-09-25 16:42:26

标签: c# asp.net-mvc smtpclient

我想将电子邮件发送给ASP.NET MVC中的多个收件人,但我发现它具有挑战性。我的代码仅发送到列表中的第一个电子邮件地址,但是我想一次发送给大约400个收件人。这些收件人的地址存储在SQL Server数据库中。这是我的代码

[HttpPost]
[ValidateInput(false)]
public ActionResult SendBulkEmail(EmailAddress ea, HttpPostedFileBase postedFile)
{
    string senderEmail = System.Configuration.ConfigurationManager.AppSettings["senderEmail"].ToString();
    string senderPassword = System.Configuration.ConfigurationManager.AppSettings["senderPassword"].ToString();

    if (ModelState.IsValid)
    {


        SqlDataReader reader;
        using (SqlConnection cs = new SqlConnection(conn))
        {
            cs.Open();
            SqlCommand cmd = new SqlCommand("SELECT email_address FROM Newsletter", cs);

            ArrayList emailArray = new ArrayList();
            reader = cmd.ExecuteReader();

            myFunctions m = new myFunctions();
            var emailList = m.LoadEmails();
            var emails = new List<AllEmailAddresses>();

            while (reader.Read())
            {
                emails.Add(new AllEmailAddresses
                {
                    EmailAddress = Convert.ToString(reader["email_address"])
                });
            }

            foreach (AllEmailAddresses email in emailList)
            {
                try
                {
                    SmtpClient client = new SmtpClient("mail.chijiokechinedu.com", 25);
                    client.Timeout = 100000;
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    client.UseDefaultCredentials = false;
                    client.Credentials = new NetworkCredential(senderEmail, senderPassword);

                    //MailMessage mailMessage = new MailMessage(senderEmail, email.EmailAddress, ea.EmailSubjest, ea.EmailBody);
                    MailMessage mailMessage = new MailMessage();
                    mailMessage.From = new MailAddress(senderEmail);
                    mailMessage.To.Add(new MailAddress(email.EmailAddress));
                    mailMessage.Subject = ea.EmailSubjest;
                    mailMessage.Body = ea.EmailBody;
                    mailMessage.IsBodyHtml = true;
                    mailMessage.BodyEncoding = UTF8Encoding.UTF8;
                    if (postedFile != null)
                    {
                        string fileName = Path.GetFileName(postedFile.FileName);
                        mailMessage.Attachments.Add(new Attachment(postedFile.InputStream, fileName));
                    }

                    client.Send(mailMessage);
                    return RedirectToAction("EmailSentSuccessfully", "Home");
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

    }
    else
    {
        ModelState.AddModelError("", "email failed to send!");
    }
    return View(ea);
}

2 个答案:

答案 0 :(得分:1)

您需要将重定向(return RedirectToAction("EmailSentSuccessfully", "Home");)移至该功能的底部,因为当您发送第一封电子邮件时,它将被重定向

[HttpPost]
[ValidateInput(false)]
public ActionResult SendBulkEmail(EmailAddress ea, HttpPostedFileBase postedFile)
{
    string senderEmail = System.Configuration.ConfigurationManager.AppSettings["senderEmail"].ToString();
    string senderPassword = System.Configuration.ConfigurationManager.AppSettings["senderPassword"].ToString();

    if (ModelState.IsValid)
    {


        SqlDataReader reader;
        using (SqlConnection cs = new SqlConnection(conn))
        {
            cs.Open();
            SqlCommand cmd = new SqlCommand("SELECT email_address FROM Newsletter", cs);

            ArrayList emailArray = new ArrayList();
            reader = cmd.ExecuteReader();

            myFunctions m = new myFunctions();
            var emailList = m.LoadEmails();
            var emails = new List<AllEmailAddresses>();

            while (reader.Read())
            {
                emails.Add(new AllEmailAddresses
                {
                    EmailAddress = Convert.ToString(reader["email_address"])
                });
            }

            foreach (AllEmailAddresses email in emailList)
            {
                SmtpClient client = new SmtpClient("mail.chijiokechinedu.com", 25);
                client.Timeout = 100000;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(senderEmail, senderPassword);

                //MailMessage mailMessage = new MailMessage(senderEmail, email.EmailAddress, ea.EmailSubjest, ea.EmailBody);
                MailMessage mailMessage = new MailMessage();
                mailMessage.From = new MailAddress(senderEmail);
                mailMessage.To.Add(new MailAddress(email.EmailAddress));
                mailMessage.Subject = ea.EmailSubjest;
                mailMessage.Body = ea.EmailBody;
                mailMessage.IsBodyHtml = true;
                mailMessage.BodyEncoding = UTF8Encoding.UTF8;
                if (postedFile != null)
                {
                    string fileName = Path.GetFileName(postedFile.FileName);
                    mailMessage.Attachments.Add(new Attachment(postedFile.InputStream, fileName));
                }

                client.Send(mailMessage);
            }

            // ** redirect after sending all the emails
            return RedirectToAction("EmailSentSuccessfully", "Home");
        }

    }
    else
    {
        ModelState.AddModelError("", "email failed to send!");
    }
    return View(ea);
}

但是,由于以下问题,您可能希望重塑方法并将其放在队列中

1)如果在发送10封电子邮件后失败了怎么办?剩下的你怎么办?

2)这是一个相当长的运行过程,如果客户端与服务器之间的连接隔离,会发生什么?

答案 1 :(得分:0)

从代码看来,您将向所有人发送完全相同的电子邮件吗? 如果是这种情况,也许您应该考虑对所有收件人使用密件抄送! 这样,您只需要发送一封电子邮件即可。批量发送邮件时,大多数邮件服务器都需要某种限制,因此,邮件越少越好。