views:

45

answers:

2

Hi,

I'm using System.Net.Mail.MailMessage to send emails from my C# Windows app.

I originally had this:

MailMessage mail = new MailMessage("[email protected]", "[email protected]");

etc which worked fine - but then I needed to add mulitple To addresses, so I changed it to this:

MailMessage mail = new MailMessage();

mail.From = new MailAddress("[email protected]");
foreach (string to in to_add)
{
    if (to.Trim() != "")
    {
        mail.To.Add(to.Trim());
    }
}

mail.Body = message;
mail.Subject = "Subject Text";

SmtpClient client = new SmtpClient("0.0.0.0");
client.UseDefaultCredentials = true;

client.Send(mail);

This code can loop through a few times, and there will be at most 3 To addresses in the string array - the first time it is run, it's fine - but then the second loop through, it hangs on

client.Send(mail);

Am I missing something here? It's the first time I've used MailMessage so it is probable that i'm missing something major.

Cheers

leddy

p.s. I'm not using the ip address "0.0.0.0", I've just removed the correct one for security reasons.

+1  A: 

You have to have a To address.

The code you posted may end up with no To address in the MailMessage.

Additionaly, the SMTP server "0.0.0.0" will not exist. This is not a valid IP address for a server - it is reserved for "Unknown".

Oded
Hi and thanks for the reply. I will add in some checking, but there should always be at least one To address (and where it hangs, there is definitely a To address there). Also I should have said, that isn't the IP address I'm using, just the one that I post on an internet forum ;)
leddy
A: 

Assuming to_add is an array of addresses, you don't need to loop through it adding them. This should work:

mail.To.Add( string.Join( ",", to_add ) );

Since you apparently had no exceptions, this will only serve to shorten your code.

The default timeout is 100 seconds. Are you waiting long enough?

Another option is to use SendAsync so it won't block.

If you haven't already read the documentation, here is a link to SmtpClient.Send on MSDN.

Austin Salonen