用于在C#/ .NET中发送电子邮件的新连接

时间:2013-07-25 09:53:36

标签: c# .net email smtp smtpclient

我在发送电子邮件时遇到问题。 webhost / emailhost指示我在一个连接中不能发送超过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);
}

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

1 个答案:

答案 0 :(得分: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语句,以确保在完成后清除所有内容。