Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send email with multiple addresses in C#

Tags:

c#

.net

email

I'm trying to send emails using gmail's username and password in a Windows application. However, the following code is sending the mail to only the first email address when I collect multiple email address in my StringBuilder instance.

var fromAddress = new MailAddress(username, DefaultSender);
var toAddress = new MailAddress(builder.ToString());//builder reference having multiple email address

string subject = txtSubject.Text;
string body = txtBody.Text; ;
var smtp = new SmtpClient
{
    Host = HostName,
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(username, password),
    //Timeout = 1000000

};
var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body,
    IsBodyHtml = chkHtmlBody.Checked

};

if (System.IO.File.Exists(txtAttechments.Text))
{
    System.Net.Mail.Attachment attechment = new  Attachment(txtAttechments.Text);
    message.Attachments.Add(attechment);
}

if(this.Enabled)
    this.Enabled = false;

smtp.Send(message);

What am I doing wrong, and how can I sort out my problem?

like image 841
Joe Avatar asked Mar 05 '11 07:03

Joe


People also ask

How to send Mail to multiple Email addresses in c#?

In the preceding class file I used a foreach loop to add the multiple recipient's Email Ids but before that we are using the comma (,) separated input email ids from user in one string "Tomail" then we are splitting the input sting with (,) commas and added to one string array named "Multi" then using a foreach loop we ...

How do I send to multiple email addresses in SMTP?

In short, to send to multiple recipients you should set the header to be a string of comma delimited email addresses. The sendmail() parameter to_addrs however should be a list of email addresses.


1 Answers

Best bet is to message.To.Add() each of your MailAddresses individually. I think early versions of .Net were happier to parse apart comma or semicolon separated email addresses than the more recent runtime versions.

like image 163
sblom Avatar answered Oct 08 '22 16:10

sblom