I have a method that update rows in a table. It goes through all the companies customer affected by the change and for each, it emails all all the users that should be notified for this change with a possible pdf file attached in it. The file is saved on the server in a specific location. This could end up into 20 to 500 emails sent from this method call.
This method is called once by the client then the server does all the job. The PDF file used for the emails is never changed, it remains the same at all time.
Maybe there is a better structure to go about this method, or some protection i can put in place to avoid the server to run out of resources when running that script?
As of now, the following error occurs: An existing connection was forcibly closed by the remote host
System.Net.SocketsException: An existing connection was forcibly closed by the remote host
Here is the stack trace the customer service sent me.
Here is most of the code of the method:
string attach = null;
string mergerFile = FileHelper.DirectoryName.MergerDocumentDirectory(instId) + mergerDocumentFileName;
if (System.IO.File.Exists(mergerFile))
attach = mergerFile;
string subject = "subject";
StringBuilder sbEmailBody = new StringBuilder();
sbEmailBody.Append("the email body etc...");
foreach(Company in companies){
//do some business logic here
foreach(User in Company.Users){
CustomLibrary.Mail.SendEmail("from@mail.com", user.Email.Trim(), "", "", subject, true, emailBody, attach);
}
}
The method CustomLibrary.Mail.SendEmail
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
smtpClient.Host = WebConfigurationManager.AppSettings["mailServer"];
smtpClient.Port = 25;
message.From = new MailAddress(EmailFrom);
message.To.Add(EmailTo);
message.Subject = EmailSubject;
#region mail body
System.Text.StringBuilder sb = new System.Text.StringBuilder();
//add some header, body and footer to the email body here
#endregion
// Message body content
message.Body = sb.ToString();
//Attachment
message.Attachments.Clear();
if (!String.IsNullOrEmpty(AttachmentFile))
{
Attachment myattach = new Attachment(AttachmentFile);
message.Attachments.Add(myattach);
}
// Send SMTP mail
smtpClient.Send(message);