.Net System.Mail.Message adding multiple "To" addresses
Asked Answered
C

10

44

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. 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 Stack Overflow archive, I'll still ask it. Maybe someone even has an idea of other traps that you can fall into.

Cochineal answered 8/3, 2010 at 20:42 Comment(3)
Glad you decided to leave your self-answering question in. This is an odd phenomenon.Alanealanine
Is your issue that it only sends to the last or that your collection is overwriting values? FWIW, in a .Net 2.0 console app, this behaves as expected (4 addresses in the To collection).Synn
We could help you out if you'd post more code...Synn
H
41

I wasn't able to replicate your bug:

var message = new MailMessage();

message.To.Add("[email protected]");
message.To.Add("[email protected]");

message.From = new MailAddress("[email protected]");
message.Subject = "Test";
message.Body = "Test";

var client = new SmtpClient("localhost", 25);
client.Send(message);

Dumping the contents of the To: MailAddressCollection:

MailAddressCollection (2 items)
DisplayName User Host Address

user example.com [email protected]
user2 example.com [email protected]

And the resulting e-mail as caught by smtp4dev:

Received: from mycomputername (mycomputername [127.0.0.1])
     by localhost (Eric Daugherty's C# Email Server)
     3/8/2010 12:50:28 PM
MIME-Version: 1.0
From: [email protected]
To: [email protected], [email protected]
Date: 8 Mar 2010 12:50:28 -0800
Subject: Test
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable

Test

Are you sure there's not some other issue going on with your code or SMTP server?

Hexahedron answered 8/3, 2010 at 20:55 Comment(3)
I'm with you. I can't reproduce this.Synn
Hmmm. Right now the mail server is down for maintenance, so I don't know of one I could test with. However, I was pretty careful, and the code I was using was very simple. But, you guys took the time to run your own tests, and multiple people. I'm still looking at my code to see if there is anything else going on. Otherwise, I'll have to tell some engineer to check out the server.Cochineal
@Matt Dawdy: You could download the linked smtp4dev to verify you are doing things correctly.Synn
N
11
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]"));
Nimrod answered 25/9, 2013 at 11:12 Comment(2)
if want to allow spaces to separate emails use this: var delimiters = new[] { ',', ';', ' ' };Tibbetts
For To.Add the separator is , ?Sperm
M
10

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

Macomber answered 8/3, 2010 at 20:52 Comment(0)
B
6

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)
Borchardt answered 8/3, 2010 at 20:58 Comment(1)
I think that if I go this route that it wants the emails separated by commas. But this then limits me in that I can't put a "user friendly" email name. Like how we used to do it years ago with "<Bob Smith> [email protected]" type construct. Maybe I have that backwards, I have forgotten now...Cochineal
S
3

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

Selina answered 8/3, 2010 at 20:47 Comment(0)
C
1

Put in addresses this code:

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

Corinecorinna answered 26/10, 2013 at 18:12 Comment(0)
N
0

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.

Novation answered 16/1, 2014 at 17:49 Comment(0)
I
0

I like the answer from Praveen, BUT, I had to adjust it somewhat to get it to work.

   public class SendmailHelper
   {
       ...
       myMail.From = from;
        string[] emails = FormatMultipleEmailAddresses(GlobalVariables.To_EMail);
        int email_counter = 0;
        while (email_counter < emails.Length)
        {
            myMail.To.Add(emails[email_counter]);
            email_counter++;
        }
        ...
    {

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

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

        return addresses;
    }
Intercept answered 25/8, 2021 at 19:20 Comment(0)
G
0

I ran into a very similar error:

$to = "[email protected];[email protected]"
$msg = New-Object Net.Mail.MailMessage($from, $to, $subject, $emailbody)

New-Object: Exception calling ".ctor" with "4" argument(s): "An invalid character was found in the mail header: ';'."

When I changed the delimiter to a comma, it works fine:

$to = "[email protected],[email protected]"
Greggrega answered 7/4, 2022 at 19:12 Comment(0)
S
-1
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);
        }

    }
}``
Shilling answered 12/7, 2016 at 4:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.