Reputation: 10287
I've got this working code to send an email using my gmail account:
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);
}
}
The problem is that I want to send the email to two recipients, not one. I can theoretically add another message to the end of that code like so:
. . .
using (var messageHH = new MailMessage(fromAddress, toAddressHH)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
{
smtp.Send(messageHH);
}
}
...sending two emails from one code block, but what I really want to do is something like this:
List<MailAddress> recipients = new List<MailAddress>();
recipients.Add(toAddress);
recipients.Add(toAddressHH);
. . .
using (var message = new MailMessage(fromAddress, recipients)
...but there seems to no such overload for MailMessage's constructor. How can I add a second recipient to the sending of an email from gmail? Both as a co-recipient and as a "CC" recipient would be nice to know.
If I do try the suggested:
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
To.Add("[email protected]", "Duckbilled Platypus")
})
...I get:
Invalid initializer member declarator
..and:
The name 'To' does not exist in the current context
I get the same with the following permutation:
To.Add(new MailAddress("[email protected]", "Duckbilled Platypus"))
Upvotes: 1
Views: 346
Reputation: 10287
I had to change the "style" of declaration, but this works:
var message = new MailMessage(fromAddress, toAddress);
message.Subject = subject;
message.Body = body;
message.To.Add(new MailAddress("[email protected]", "Duckbilled Platypus"));
message.To.Add(new MailAddress("[email protected]", "Platypus 2"));
smtp.Send(message);
Upvotes: 0
Reputation: 371
Looking at Microsoft's Documentation, you can see that the MailMessage.To property is a MailAddressCollection.
The MailAddressCollection has an Add() method that will append values to the collection.
With that information, you can try something like this:
messageHH.To.Add(new MailAddress("[email protected]","Recipient1 Name"));
messageHH.To.Add(new MailAddress("[email protected]","Recipient2 Name"));
messageHH.To.Add(new MailAddress("[email protected]","Recipient3 Name"));
//etc...
Upvotes: 2