public void Import(IConfig config) { SmtpHost = config.GetSections("sendmail/smtp").Select(host => { SendMailHostData hostData = new SendMailHostData(); hostData.Address = host.Get("address"); hostData.Port = int.Parse(host.Get("port")); hostData.UseSSL = host.Get("ssl", false) == "true"; hostData.Username = host.Get("username", false); hostData.Password = GetPassword(host); hostData.From = host.Get("from", false); return(hostData); }) .ToArray(); }
/// <summary> /// Send Email /// </summary> /// <param name="sendMailHost"></param> /// <param name="message">Message to send</param> public virtual bool Post(SendMailHostData sendMailHost, MailMessage message) { try { if (!string.IsNullOrEmpty(sendMailHost.From)) { message.From = new MailAddress(sendMailHost.From); } var client = new SmtpClient(sendMailHost.Address, sendMailHost.Port); try { client.Timeout = 10; client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential(sendMailHost.Username, sendMailHost.Password); client.EnableSsl = sendMailHost.UseSSL; #if NETSTANDARD2_0 if (client.SendMailAsync(message).Wait(TimeSpan.FromSeconds(client.Timeout))) { return(true); } throw new TimeoutException(); #endif #if NETFX using (var send = new SendMailWorker()) { send.Run(() => client.Send(message)); if (send.WaitOne(TimeSpan.FromSeconds(client.Timeout)) == false) { throw new TimeoutException(); } } return(true); #endif } finally { #if NETSTANDARD2_0 client.Dispose(); #endif } } catch (SmtpException ex) { Logger.Error(ex.Message + ex.InnerException + ex.StatusCode); return(false); } catch (Exception ex) { Logger.Error($"Unable send email through smtp {sendMailHost.Address}:{sendMailHost.Port}"); if (Logger.DebugEnabled) { Logger.Debug(ex.ToString()); } return(false); } }