[asp.net] .Net System.Mail.Message adding multiple "To" addresses

EDIT: This question is pointless, except as an exercise in red herrings. The issue turned out to be a combination of my idiocy (NO ONE was being emailed as the host was not being specified and was incorrect in web.config) and the users telling me that they sometimes got the emails and sometimes didn't, when in reality they were NEVER getting the emails.

So, instead of taking proper steps to reproduce the problem in a controlled setting, I relied on user information and the "it works on my machine" mentality. Good reminder to myself and anyone else out there who is sometimes an idiot.


I just hit something I think is inconsistent, and wanted to see if I'm doing something wrong, if I'm an idiot, or...

MailMessage msg = new MailMessage();
msg.To.Add("[email protected]");
msg.To.Add("[email protected]");
msg.To.Add("[email protected]");
msg.To.Add("[email protected]");

Really only sends this email to 1 person, the last one.

To add multiples I have to do this:

msg.To.Add("[email protected],[email protected],[email protected],[email protected]");

I don't get it. I thought I was adding multiple people to the To address collection, but what I was doing was replacing it.

I think I just realized my error -- to add one item to the collection, use .To.Add(new MailAddress("[email protected]"))

If you use just a string, it replaces everything it had in its list. EDIT: Other people have tested and are not seeing this behavior. This is either a bug in my particular version of the framework, or more likely, an idiot maneuver by me.

Ugh. I'd consider this a rather large gotcha! Since I answered my own question, but I think this is of value to have in the stackoverflow archive, I'll still ask it. Maybe someone even has an idea of other traps that you can fall into.

This question is related to asp.net system.net.mail

The answer is


Put in addresses this code:

objMessage.To.Add(***addresses:=***"[email protected] , [email protected] , [email protected]")


You could try putting the e-mails into a comma-delimited string ("[email protected], [email protected]"):

C#:

ArrayList arEmails = new ArrayList();
arEmails.Add("[email protected]");
arEmails.Add("[email protected]");
           
string strEmails = string.Join(", ", arEmails);

VB.NET if you're interested:

Dim arEmails As New ArrayList
arEmails.Add("[email protected]")
arEmails.Add("[email protected]")

Dim strEmails As String = String.Join(", ", arEmails)

private string FormatMultipleEmailAddresses(string emailAddresses)
    {
      var delimiters = new[] { ',', ';' };

      var addresses = emailAddresses.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

      return string.Join(",", addresses);
    }

Now you can use it like

var mailMessage = new MailMessage();
mailMessage.To.Add(FormatMultipleEmailAddresses("[email protected];[email protected],[email protected]"));

Add multiple System.MailAdress object to get what you want.


You can do this either with multiple System.Net.Mail.MailAddress objects or you can provide a single string containing all of the addresses separated by commas


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Web;

namespace HMS.HtmlHelper
{
    public class SendmailHelper
    {
        //Created SendEMail method for sendiing mails to users 
        public bool SendEMail(string FromName, string ToAddress, string Subject, string Message)
        {
            bool valid =false;
            try
            {
                string smtpUserName = System.Configuration.ConfigurationManager.AppSettings["smtpusername"].ToString();
                string smtpPassword = System.Configuration.ConfigurationManager.AppSettings["smtppassword"].ToString();
                MailMessage mail = new MailMessage();``
                mail.From = new MailAddress(smtpUserName, FromName);
                mail.Subject = Subject;
                mail.To.Add(FormatMultipleEmailAddresses(ToAddress));
                //mail.To.Add(ToAddress);
                mail.Body = Message.ToString();
                mail.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["smtpserverport"]);
                smtp.Host = System.Configuration.ConfigurationManager.AppSettings["SmtpServer"]; /
                smtp.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpPassword);
                smtp.EnableSsl = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["ssl"]); ;
                smtp.Send(mail);
                valid = true;

            }
            catch (Exception ex)
            {
                valid =false ;
            }

            return valid;
        }



        public string FormatMultipleEmailAddresses(string emailAddresses)
        {
            var delimiters = new[] { ',', ';' };

            var addresses = emailAddresses.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

            return string.Join(",", addresses);
        }

    }
}``

Thanks for spotting this I was about to add strings thinking the same as you that they'd get added to end of collection. It appears the params are:

msg.to.Add(<MailAddress>) adds MailAddress to the end of the collection
msg.to.Add(<string>) add a list of emails to the collection

Slightly different actions depending on param type, I think this is pretty bad form i'd have prefered split methods AddStringList of something.