[c#] How to send email to multiple address using System.Net.Mail

I have smtp email functionality. it works for single address but has problem in multiple address.

i am passing multiple addresses using following line of code.

MailAddress to = new MailAddress("[email protected],[email protected]");

Please let me know the problem as i am not getting any error.

This question is related to c# .net smtp

The answer is


MailAddress fromAddress = new MailAddress  (fromMail,fromName);
MailAddress toAddress = new MailAddress(toMail,toName);
MailMessage message = new MailMessage(fromAddress,toAddress);
message.Subject = subject;
message.Body = body;
SmtpClient smtp = new SmtpClient()
{
    Host = host, Port = port,
    enabHost = "smtp.gmail.com",
    Port = 25,
    EnableSsl = true,
    UseDefaultCredentials = true,
    Credentials = new  NetworkCredentials (fromMail, password)
};
smtp.send(message);

StewieFG suggestion is valid but if you want to add the recipient name use this, with what Marco has posted above but is email address first and display name second:

msg.To.Add(new MailAddress("[email protected]","Your name 1"));
msg.To.Add(new MailAddress("[email protected]","Your name 2"));

My code to solve this problem:

private void sendMail()
{   
    //This list can be a parameter of metothd
    List<MailAddress> lst = new List<MailAddress>();

    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));


    try
    {


        MailMessage objeto_mail = new MailMessage();
        SmtpClient client = new SmtpClient();
        client.Port = 25;
        client.Host = "10.15.130.28"; //or SMTP name
        client.Timeout = 10000;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
        objeto_mail.From = new MailAddress("[email protected]");

        //add each email adress
        foreach (MailAddress m in lst)
        {
            objeto_mail.To.Add(m);
        }


        objeto_mail.Subject = "Sending mail test";
        objeto_mail.Body = "Functional test for automatic mail :-)";
        client.Send(objeto_mail);


    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

I'm used "for" operator.

try
{
    string s = textBox2.Text;
    string[] f = s.Split(',');

    for (int i = 0; i < f.Length; i++)
    {
        MailMessage message = new MailMessage(); // Create instance of message
        message.To.Add(f[i]); // Add receiver
        message.From = new System.Net.Mail.MailAddress(c);// Set sender .In this case the same as the username
        message.Subject = label3.Text; // Set subject
        message.Body = richTextBox1.Text; // Set body of message
        client.Send(message); // Send the message
        message = null; // Clean up
    }

}

catch (Exception ex)
{

    MessageBox.Show(ex.Message);
}

I think you can use this code in order to have List of outgoing Addresses having a display Name (also different):

//1.The ACCOUNT
MailAddress fromAddress = new MailAddress("[email protected]", "my display name");
String fromPassword = "password";

//2.The Destination email Addresses
MailAddressCollection TO_addressList = new MailAddressCollection();

//3.Prepare the Destination email Addresses list
foreach (var curr_address in mailto.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))
{
    MailAddress mytoAddress = new MailAddress(curr_address, "Custom display name");
    TO_addressList.Add(mytoAddress);
}

//4.The Email Body Message
String body = bodymsg;

//5.Prepare GMAIL SMTP: with SSL on port 587
var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
    Timeout = 30000
};


//6.Complete the message and SEND the email:
using (var message = new MailMessage()
        {
            From = fromAddress,
            Subject = subject,
            Body = body,
        })
{
    message.To.Add(TO_addressList.ToString());
    smtp.Send(message);
}

namespace WebForms.Code.Logging {

    public class ObserverLogToEmail: ILog {
        private string from;
        private string to;
        private string subject;
        private string body;
        private SmtpClient smtpClient;
        private MailMessage mailMessage;
        private MailPriority mailPriority;
        private MailAddressCollection mailAddressCollection;
        private MailAddress fromMailAddress, toMailAddress;
        public MailAddressCollection toMailAddressCollection {
            get;
            set;
        }
        public MailAddressCollection ccMailAddressCollection {
            get;
            set;
        }
        public MailAddressCollection bccMailAddressCollection {
            get;
            set;
        }

        public ObserverLogToEmail(string from, string to, string subject, string body, SmtpClient smtpClient) {
            this.from = from;
            this.to = to;
            this.subject = subject;
            this.body = body;

            this.smtpClient = smtpClient;
        }

        public ObserverLogToEmail(MailAddress fromMailAddress, MailAddress toMailAddress,
        string subject, string content, SmtpClient smtpClient) {
            try {
                this.fromMailAddress = fromMailAddress;
                this.toMailAddress = toMailAddress;
                this.subject = subject;
                this.body = content;

                this.smtpClient = smtpClient;

                mailAddressCollection = new MailAddressCollection();

            } catch {
                throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
            }
        }

        public ObserverLogToEmail(MailAddressCollection fromMailAddressCollection,
        MailAddressCollection toMailAddressCollection,
        string subject, string content, SmtpClient smtpClient) {
            try {
                this.toMailAddressCollection = toMailAddressCollection;
                this.ccMailAddressCollection = ccMailAddressCollection;
                this.subject = subject;
                this.body = content;

                this.smtpClient = smtpClient;

            } catch {
                throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
            }
        }

        public ObserverLogToEmail(MailAddressCollection toMailAddressCollection,
        MailAddressCollection ccMailAddressCollection,
        MailAddressCollection bccMailAddressCollection,
        string subject, string content, SmtpClient smtpClient) {
            try {
                this.toMailAddressCollection = toMailAddressCollection;
                this.ccMailAddressCollection = ccMailAddressCollection;
                this.bccMailAddressCollection = bccMailAddressCollection;

                this.subject = subject;
                this.body = content;

                this.smtpClient = smtpClient;

            } catch {
                throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
            }
        }#region ILog Members

        // sends a log request via email.
        // actual email 'Send' calls are commented out.
        // uncomment if you have the proper email privileges.
        public void Log(object sender, LogEventArgs e) {
            string message = "[" + e.Date.ToString() + "] " + e.SeverityString + ": " + e.Message;
            fromMailAddress = new MailAddress("", "HaNN", System.Text.Encoding.UTF8);
            toMailAddress = new MailAddress("", "XXX", System.Text.Encoding.UTF8);

            mailMessage = new MailMessage(fromMailAddress, toMailAddress);
            mailMessage.Subject = subject;
            mailMessage.Body = body;

            // commented out for now. you need privileges to send email.
            // _smtpClient.Send(from, to, subject, body);
            smtpClient.Send(mailMessage);
        }

        public void LogAllEmails(object sender, LogEventArgs e) {
            try {
                string message = "[" + e.Date.ToString() + "] " + e.SeverityString + ": " + e.Message;

                mailMessage = new MailMessage();
                mailMessage.Subject = subject;
                mailMessage.Body = body;

                foreach(MailAddress toMailAddress in toMailAddressCollection) {
                    mailMessage.To.Add(toMailAddress);

                }
                foreach(MailAddress ccMailAddress in ccMailAddressCollection) {
                    mailMessage.CC.Add(ccMailAddress);
                }
                foreach(MailAddress bccMailAddress in bccMailAddressCollection) {
                    mailMessage.Bcc.Add(bccMailAddress);
                }
                if (smtpClient == null) {
                    var smtp = new SmtpClient {
                        Host = "smtp.gmail.com",
                        Port = 587,
                        EnableSsl = true,
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Credentials = new NetworkCredential("yourEmailAddress", "yourPassword"),
                        Timeout = 30000
                    };
                } else smtpClient.SendAsync(mailMessage, null);
            } catch (Exception) {

                throw;
            }
        }
    }

try this..

using System;
using System.Net.Mail;

public class Test
{
    public static void Main()
    {
        SmtpClient client = new SmtpClient("smtphost", 25);
        MailMessage msg = new MailMessage("[email protected]", "[email protected],[email protected]");
        msg.Subject = "sdfdsf";
        msg.Body = "sdfsdfdsfd";
        client.UseDefaultCredentials = true;
        client.Send(msg);
    }
}

 string[] MultiEmails = email.Split(',');
 foreach (string ToEmail in MultiEmails)
 {
    message.To.Add(new MailAddress(ToEmail)); //adding multiple email addresses
 }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to smtp

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error PHPMailer - SMTP ERROR: Password command failed when send mail from my server php function mail() isn't working Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required "An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14" SmtpException: Unable to read data from the transport connection: net_io_connectionclosed How to configure SMTP settings in web.config Send mail via CMD console Mail not sending with PHPMailer over SSL using SMTP