[英]How can I include multiple recipients in a gmail email message?
我有以下工作代码可以使用我的gmail帐户发送电子邮件:
public static void SendEmail(string fullName, string toEmail, string HH, string HHEmailAddr)
{
var fromAddress = new MailAddress(FROM_EMAIL, FROM_EMAIL_NAME);
var toAddress = new MailAddress(toEmail, fullName);
var toAddressHH = new MailAddress(HHEmailAddr, HH);
string fromPassword = GMAIL_PASSWORD;
List<String> htmlBody = new List<string>
{
"<html><body>",
. . .
"</body></html>"
};
var body = string.Join("", htmlBody.ToArray());
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
{
smtp.Send(message);
}
}
问题是我想将电子邮件发送给两个收件人,而不是一个。 从理论上讲,我可以在该代码的末尾添加另一条消息,如下所示:
. . .
using (var messageHH = new MailMessage(fromAddress, toAddressHH)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
{
smtp.Send(messageHH);
}
}
...从一个代码块发送两封电子邮件,但是我真正想要做的是这样的:
List<MailAddress> recipients = new List<MailAddress>();
recipients.Add(toAddress);
recipients.Add(toAddressHH);
. . .
using (var message = new MailMessage(fromAddress, recipients)
...但是对于MailMessage的构造函数来说似乎没有这样的重载。 如何在通过gmail发送电子邮件时添加第二个收件人? 作为共同收件人和“ CC”收件人,都将很高兴知道。
如果我尝试尝试建议:
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
To.Add("dplatypus@att.net", "Duckbilled Platypus")
})
...我得到:
无效的初始化器成员声明器
..和:
名称“ To”在当前上下文中不存在
我得到以下排列相同:
To.Add(new MailAddress("dplatypus@att.net", "Duckbilled Platypus"))
查看Microsoft的Documentation ,您可以看到MailMessage.To属性是MailAddressCollection。
MailAddressCollection具有一个Add()方法,该方法会将值附加到集合中。
有了这些信息,您可以尝试如下操作:
messageHH.To.Add(new MailAddress("recipient1@domain.com","Recipient1 Name"));
messageHH.To.Add(new MailAddress("recipient2@domain.com","Recipient2 Name"));
messageHH.To.Add(new MailAddress("recipient3@domain.com","Recipient3 Name"));
//etc...
我不得不更改声明的“样式”,但这可以起作用:
var message = new MailMessage(fromAddress, toAddress);
message.Subject = subject;
message.Body = body;
message.To.Add(new MailAddress("dplatypus@att.net", "Duckbilled Platypus"));
message.To.Add(new MailAddress("duckbill@att.net", "Platypus 2"));
smtp.Send(message);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.