Pergunta

I am facing a problem in sending email. The webhost/emailhost instructed me that I can not send more than 10 emails in one connection. I was sending 30-40 emails using the following code:

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);
}

But now if I put the code

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

in the for loop like:

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);
}

then will it create a new connection with the server every time email is sent? Or should I wait for a few minutes to make sure a previous connection expires before creating a new one? I mean I do not know how to create a new connection for each email that I send and how to ensure that I send each email with a new connection with the email server.

Foi útil?

Solução

Change your code to the following:

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);
}

Than you can be sure that the connection will be closed. Try to always use a using statement on disposable objects, to make sure everything is cleared after you are done.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top