开发者

changed MailMessage properties, now it's hanging on client.Send

开发者 https://www.devze.com 2022-12-14 05:56 出处:网络
I\'m using System.Net.Mail.MailMessage to send emails from my C# Windows app. I originally had this: MailMessage mail = new MailMessage(\"from@address.com\", \"to@address.com\");

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

I originally had this:

MailMessage mail = new MailMessage("from@address.com", "to@address.com");

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("from@address.com");
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 t开发者_如何学编程imes, 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.


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".


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.


The MailMessage class implements IDiposable, so perhaps it's because you are not disposing of it?

Also, before .NET 4.0, the System.Net.Mail.SmtpClient was not disposable but in 4.0 it implements IDisposable, so you'd want to wrap it in a using statement as well. The code would look like:

using (MailMessage mail = new MailMessage())
{
    mail.From = new MailAddress("from@address.com");
    mail.To.Add(string.Join(",", to_add ));
    mail.Body = message;
    mail.Subject = "Subject Text";

    using (SmtpClient client = new SmtpClient("0.0.0.0"))
    {
        client.UseDefaultCredentials = true;
        client.Send(mail);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消