public void Dispose() { smtpServer.Dispose(); smtpServer = null; }
public void Stop() { server.Dispose(); }
private static bool SendEmail(string frSendEmail, string toSendEmail, string usrEmail, string pwdEmail, string hostEmail, int?portEmail, string subjectEmail, string bodyEmail, string[] attachFiles, int loopSendEmailErr, string[] logData) { bool result = false; MailMessage mail = null; SmtpClient SmtpServer = null; try { if (!string.IsNullOrEmpty(frSendEmail) && !string.IsNullOrEmpty(toSendEmail) && !string.IsNullOrEmpty(hostEmail)) { mail = new MailMessage(); SmtpServer = new SmtpClient(hostEmail); mail.From = new MailAddress(frSendEmail); Array.ForEach(toSendEmail.Split(';'), c => { mail.To.Add(c); } ); mail.Subject = subjectEmail; mail.IsBodyHtml = true; mail.Body = bodyEmail; if (attachFiles != null && attachFiles.Length > 0) { Array.ForEach( attachFiles, filePath => { mail.Attachments.Add(new System.Net.Mail.Attachment(filePath)); } ); } if (portEmail.HasValue) { SmtpServer.Port = portEmail.Value; } if (!string.IsNullOrEmpty(usrEmail) && !string.IsNullOrEmpty(pwdEmail)) { SmtpServer.UseDefaultCredentials = false; SmtpServer.Credentials = new System.Net.NetworkCredential(usrEmail, pwdEmail); SmtpServer.EnableSsl = true; SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network; } for (int i = 1; i <= loopSendEmailErr; i++) { try { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); SmtpServer.Send(mail); result = true; stopwatch.Stop(); var msg = $"Time elapsed: {ConvertMillisecondsToSeconds(stopwatch.ElapsedMilliseconds)} seconds"; } catch (Exception ex) { result = false; } if (result == false && i != loopSendEmailErr) { System.Threading.Thread.Sleep(60000); // waiting resend email. } else if (result) { i = (loopSendEmailErr + 1); // out loop send completed. } else if (i == loopSendEmailErr) { i++; // out loop send error } } } else { result = false; } } catch (Exception ex) { result = false; } finally { if (SmtpServer != null) { SmtpServer.Dispose(); SmtpServer = null; } if (mail != null) { mail.Dispose(); mail.Dispose(); mail = null; } } return(result); }