如何在Gmail电子邮件中包含多个收件人?

时间:2016-03-08 14:41:17

标签: c# email smtp mailmessage

我有这个工作代码使用我的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发送电子邮件时添加第二个收件人?作为共同接受者和作为&#34; CC&#34;收件人很高兴知道。

更新

如果我尝试建议:

using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body,
    To.Add("dplatypus@att.net", "Duckbilled Platypus")
})

......我明白了:

无效的初始化成员声明符

..和

名称&#39; To&#39;在当前上下文中不存在

我通过以下排列获得相同的结果:

To.Add(new MailAddress("dplatypus@att.net", "Duckbilled Platypus"))

2 个答案:

答案 0 :(得分:2)

查看Microsoft's 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...

答案 1 :(得分:0)

我不得不改变宣言的“风格”,但这有效:

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