我正在尝试发送在我的Userprofiles表中列出的电子邮件,我还添加了2列,如PhoneNo和Email。并且还在此表中添加了值。我希望一次发送这些列出的人员的电子邮件。现在它一次只发送一封邮件。我试过这段代码,但它无法正常工作。请帮助..
public ActionResult SendEmail(string address, string subject, string message)
{
if (ModelState.IsValid)
{
var v = (from e in db.todaySalesReport()
select e).SingleOrDefault();
var ctx = new UsersContext();
string from = "";
foreach (var i in ctx.UserProfiles.ToList())
{
address = i.Email;
//MailAddress addr = new MailAddress();
using (MailMessage mail = new MailMessage(from, address))
{
mail.To.Add(i.Email);
mail.Subject = "Total Sales Report for today";
mail.Body = "Total sales" + v.qty.ToString() + "Peices.";
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential networkCredential = new NetworkCredential(from, "");
smtp.UseDefaultCredentials = false;
smtp.Credentials = networkCredential;
smtp.Port = 587;
smtp.Send(mail);
ViewBag.Message = "Sent";
return View("Index", address);
}
}
}
else
{
return View();
}
return RedirectToAction("Index");
}
答案 0 :(得分:2)
这是因为您要在foreach循环中返回视图。将此代码从foreach循环中取出:
return View("Index", address);
应该是这样的:
if (ModelState.IsValid)
{
var v = (from e in db.todaySalesReport()
select e).SingleOrDefault();
var ctx = new UsersContext();
string from = "";
foreach (var i in ctx.UserProfiles.ToList())
{
address = i.Email;
//MailAddress addr = new MailAddress();
using (MailMessage mail = new MailMessage(from, address))
{
mail.To.Add(i.Email);
mail.Subject = "Total Sales Report for today";
mail.Body = "Total sales" + v.qty.ToString() + "Peices.";
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential networkCredential = new NetworkCredential(from, "");
smtp.UseDefaultCredentials = false;
smtp.Credentials = networkCredential;
smtp.Port = 587;
smtp.Send(mail);
ViewBag.Message = "Sent";
}
}
return View("Index", address);
}
答案 1 :(得分:1)
你有这个
return View("Index", address);
在你的循环结束时晃来晃去。将它移出循环,它应该没问题。