0

我在发送电子邮件时遇到问题。网络主机/电子邮件主机指示我不能在一个连接中发送超过 10 封电子邮件。我使用以下代码发送了 30-40 封电子邮件:

SmtpClient emailServer = new SmtpClient("Server");
emailServer.Credentials = new System.Net.NetworkCredential("Username", "Password");

for (int iCount = 0; iCount < listEmail.Count; iCount++)
{
   MailMessage email = new MailMessage();
   email.From = new MailAddress("from");
   email.Subject = "Subject";
   email.To.Add(listEmail[iCount]);

   emailServer.Send(email);
}

但是现在如果我把代码

SmtpClient emailServer = new SmtpClient("Server");
emailServer.Credentials = new System.Net.NetworkCredential("Username", "Password");

for循环中,如:

for (int iCount = 0; iCount < listEmail.Count; iCount++)
{    
   SmtpClient emailServer = new SmtpClient("Server");
   emailServer.Credentials = new System.Net.NetworkCredential("Username", "Password");

   MailMessage email = new MailMessage();
   email.From = new MailAddress("from");
   email.Subject = "Subject";
   email.To.Add(listEmail[iCount]);

   emailServer.Send(email);
}

那么它会在每次发送电子邮件时与服务器建立新的连接吗?或者我应该等待几分钟以确保以前的连接过期,然后再创建新连接?我的意思是我不知道如何为我发送的每封电子邮件创建一个新连接,以及如何确保我发送的每封电子邮件都与电子邮件服务器建立新连接。

4

1 回答 1

3

将您的代码更改为以下内容:

using (var emailServer = new SmtpClient("Server"))
{
   emailServer.Credentials = new System.Net.NetworkCredential("Username", "Password");

   MailMessage email = new MailMessage();
   email.From = new MailAddress("from");
   email.Subject = "Subject";
   email.To.Add(listEmail[iCount]);

   emailServer.Send(email);
}

你可以确定连接将被关闭。尝试始终对一次性对象使用 using 语句,以确保在完成后清除所有内容。

于 2013-07-25T10:00:21.960 回答