问题
I am sending emails using c# using SmtpClient. I have to send aproximately one hundred different emails per day, and I can't use the same mail (adding several recipients) since the email changes according to the recipient.
I am not using a local SMTP server, and I understand (according to @rizzle response here) that some time has to be left between one mail and another one. However, I am sleeping my program for 10 seconds and still, it is only the first email that gets sent, never the second one (so far I am trying my system with two emails instead of one hundred). This is my code, any ideas?
foreach (Person p in clientList)
{
AlternateView plainView = AlternateView.CreateAlternateViewFromString("Texto visible para clientes que no tienen HTML", null, "text/plain");
//AlternateView htmlView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.<img src=cid:companylogo>", null, "text/html");
string htmlString = "html string body of the email";
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlString, null, "text/html");
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.AlternateViews.Add(htmlView);
message.To.Add(p.email.Trim());
message.Subject = p.nombre+", email subject";
message.From = new System.Net.Mail.MailAddress(fromAddress);
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("...");
NetworkCredential myCreds = new NetworkCredential(usr, pass, "");
client.Credentials = myCreds;
client.Send(message);
System.Threading.Thread.Sleep(10000);
}
回答1:
Do client.Dispose()
right after you send your last message, if you're on dotnet 4. This will force the dotnet SMTP stuff to finish its work.
See here: System.Net.Mail and MailMessage not Sending Messages Immediately
If you're on earlier versions of DotNet, try doing a couple of things.
Do message.Dispose()
when you're done with the message instance.
Define your SmtpClient locally (within a method) and exit the method when you're done sending. That is, don't try to keep your client instance around as a field in one of your long-lived class instances; it won't flush the last message you sent to the server until it's finalized.
(They really did fix this in dotnet 4.0)
回答2:
In 3.5 try using:
SmtpClient client = ...
client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
using (MailMessage message = ...)
{
// where userToken is a user-defined token
// to be passed to the SendCompletedCallback
client.SendAsync(message, userToken);
} // Disposes of message
Then in the SendCompletedCallback
trigger the next...
SmtpClient Class
来源:https://stackoverflow.com/questions/8079605/why-cant-i-send-two-mails-in-a-row-with-c