我想返回所有管理员的电子邮件地址,然后向他们发送电子邮件。现在我只能发送到一个电子邮件地址,我必须硬编码(我的意思是我必须硬编码)。但我想根据我的电子邮件数组发送多封电子邮件
// Here is my first problem, to save them in array
public string UserEmails()
{
var emails = context.Users.Where(u => u.IsAdmin == true).Select(e => e.Email).ToArray();
// First question, How to save those emails into an array and return those email array then to use it in my SendEmailToUser();
}
这是我的SendEmailToUser()
public JsonResult SendEmailToUser()
{
bool result = false;
// My second question, Here I want to put those email array, But I don't know how to do
// If I hardcoded with one email .. let say test@gmail.com, works fine
// But instead to send to one email address , I want to send to thos emails which are in my array
result = SendEmail("emails from array", "Here is my subject", "<p>Here is my message</p>");
return Json(result, JsonRequestBehavior.AllowGet);
}
这是我的SendEmail(适用于一个硬编码的电子邮件地址)
public bool SendEmail(string toEmail, string subject, string emailBody)
{
try
{
string senderEmail = System.Configuration.ConfigurationManager.AppSettings["SenderEmail"].ToString();
string senderPassword = System.Configuration.ConfigurationManager.AppSettings["SenderPassword"].ToString();
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(senderEmail, senderPassword);
MailMessage mailMessage = new MailMessage(senderEmail, toEmail, subject, emailBody);
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = UTF8Encoding.UTF8;
client.Send(mailMessage);
return true;
}
catch(Exception ex)
{
return false;
}
}
答案 0 :(得分:0)
您可以遍历数组并为每封电子邮件调用方法。
使用foreach
方法
var emails = context.Users
.Where(u => u.IsAdmin)
.Select(e => e.Email).ToArray();
foreach(var email in emails)
{
SendEmail(email , "subject","email body");
}
假设Email
属性是存储电子邮件地址的字符串类型。
如果您想要返回此电子邮件数组的方法,只需将方法的返回类型更改为字符串数组。
public string[] UserEmails()
{
return context.Users
.Where(u => u.IsAdmin == true)
.Select(e => e.Email)
.ToArray();
}
在您的其他方法中,您可以调用此方法。
var emails = UserEmails();
foreach(var email in emails)
{
SendEmail(email , "subject","email body");
}
请记住,这会多次调用SendEmail方法,一次调用电子邮件数组中的每个项目。 MailMessage.To
method允许您向多个人发送一封电子邮件(“收件人”地址中的许多人),如果这就是您所追求的目的。