public static string Authorize(this BaseProtocolClient ingoingMailClient, MailServerSettings settings, int waitTimeout = 5000, ILogger log = null) { if (log == null) { log = new NullLogger(); } string lastResponse; switch (settings.EncryptionType) { case EncryptionType.SSL: //var timeout = TimeSpan.FromMinutes(3); // 3 minutes log.Debug("SSL connecting to {0} ", settings.Url); // (timeout = {1} minutes)", settings.Url, timeout.TotalMinutes); lastResponse = ingoingMailClient.ConnectSsl(settings.Url, settings.Port); //, (int)timeout.TotalMilliseconds); break; default: log.Debug("PLAIN connecting to {0}", settings.Url); lastResponse = ingoingMailClient.ConnectPlain(settings.Url, settings.Port); if (ingoingMailClient is SmtpClient && (settings.AuthenticationType != SaslMechanism.None || settings.EncryptionType == EncryptionType.StartTLS)) { lastResponse = ingoingMailClient.SendEhloHelo(); } if (settings.EncryptionType == EncryptionType.StartTLS) { log.Debug("StartTLS {0}", settings.Url); lastResponse = ingoingMailClient.StartTLS(settings.Url); } break; } if (settings.AuthenticationType == SaslMechanism.Login) { log.Debug("Login as {0} with secret password", settings.AccountName); lastResponse = ingoingMailClient.Login(settings.AccountName, settings.AccountPass); } else { if (ingoingMailClient is SmtpClient && settings.AuthenticationType == SaslMechanism.None) { log.Debug("Authentication not required"); return(lastResponse); } log.Debug("Authenticate as {0} with secret password", settings.AccountName); lastResponse = ingoingMailClient.Authenticate(settings.AccountName, settings.AccountPass, settings.AuthenticationType); } return(lastResponse); }
public static string Authorize(this BaseProtocolClient ingoingMailClient, MailServerSettings settings, int waitTimeout = 5000, ILogger log = null) { if (log == null) log = new NullLogger(); string lastResponse; switch (settings.EncryptionType) { case EncryptionType.SSL: var timeout = TimeSpan.FromMinutes(3); // 3 minutes log.Debug("SSL connecting to {0} (timeout = {1} minutes)", settings.Url, timeout.TotalMinutes); lastResponse = ingoingMailClient.ConnectSsl(settings.Url, settings.Port, (int)timeout.TotalMilliseconds); break; default: log.Debug("PLAIN connecting to {0}", settings.Url); lastResponse = ingoingMailClient.ConnectPlain(settings.Url, settings.Port); if (ingoingMailClient is SmtpClient && (settings.AuthenticationType != SaslMechanism.None || settings.EncryptionType == EncryptionType.StartTLS)) { lastResponse = ingoingMailClient.SendEhloHelo(); } if (settings.EncryptionType == EncryptionType.StartTLS) { log.Debug("StartTLS {0}", settings.Url); lastResponse = ingoingMailClient.StartTLS(settings.Url); } break; } if (settings.AuthenticationType == SaslMechanism.Login) { log.Debug("Login as {0} with secret password", settings.AccountName); lastResponse = ingoingMailClient.Login(settings.AccountName, settings.AccountPass); } else { if (ingoingMailClient is SmtpClient && settings.AuthenticationType == SaslMechanism.None) { log.Debug("Authentication not required"); return lastResponse; } log.Debug("Authenticate as {0} with secret password", settings.AccountName); lastResponse = ingoingMailClient.Authenticate(settings.AccountName, settings.AccountPass, settings.AuthenticationType); } return lastResponse; }
/// <summary> /// Sends a RFC conform email using default .NET classes. /// </summary> /// <param name="messageToSend">The pre-configured <see cref="MailMessage" /> to send.</param> /// <param name="settings">A structure containing the settings for the server.</param> /// <returns><c>True</c> if the mail was sent, otherwise <c>false</c>.</returns> public static async Task <bool> SendMailAsync(MailMessage messageToSend, MailServerSettings settings) { CheckUtil.ThrowIfNull(() => messageToSend); try { // Send the mail and use credentials if given. using (var client = new SmtpClient(settings.ServerAddress, settings.Port)) { if (settings.UseDefaultCredentials) { client.Credentials = CredentialCache.DefaultNetworkCredentials; } else { if (!string.IsNullOrEmpty(settings.Username) && !string.IsNullOrEmpty(settings.Password)) { client.Credentials = new NetworkCredential(settings.Username, settings.Password, settings.Domain ?? string.Empty); } } await client.SendMailAsync(messageToSend); } return(true); } catch (Exception ex) { var error = string.Format( CultureInfo.InvariantCulture, "Cannot send e-mail from '{0}' to '{1}' with subject '{2}': {3}", messageToSend.From, messageToSend.To, messageToSend.Subject, ex); var file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments), "mail.error"); using (var writer = File.AppendText(file)) { writer.Write(error); writer.Close(); } throw new InvalidOperationException(error, ex); } }
public int SaveMailServerSettings(MailAddress email, MailServerSettings settings, string serverType, AuthorizationServiceType authorizationType) { var host = (authorizationType == AuthorizationServiceType.Google) ? GOOGLE_HOST : email.Host; using (var db = GetDb()) { var providerId = db.ExecuteScalar<int>(new SqlQuery(MailboxDomainTable.name) .Select(MailboxDomainTable.Columns.id_provider) .Where(MailboxProviderTable.Columns.name, host)); //Save Mailbox provider if not exists if (providerId == 0) { providerId = db.ExecuteScalar<int>(new SqlInsert(MailboxProviderTable.name) .InColumnValue(MailboxProviderTable.Columns.id, 0) .InColumnValue(MailboxProviderTable.Columns.name, email.Host) .Identity(0, 0, true)); db.ExecuteNonQuery(new SqlInsert(MailboxDomainTable.name) .InColumnValue(MailboxDomainTable.Columns.id_provider, providerId) .InColumnValue(MailboxDomainTable.Columns.name, email.Host)); } //Identify mask for account name var accountNameMask = ""; if (settings.AuthenticationType != SaslMechanism.None) { accountNameMask = GetLoginFormatFrom(email, settings.AccountName); if (String.IsNullOrEmpty(accountNameMask)) { accountNameMask = settings.AccountName; } } var settingsId = db.ExecuteScalar<int>(new SqlQuery(MailboxServerTable.name) .Select(MailboxServerTable.Columns.id) .Where(MailboxServerTable.Columns.id_provider, providerId) .Where(MailboxServerTable.Columns.type, serverType) .Where(MailboxServerTable.Columns.hostname, settings.Url) .Where(MailboxServerTable.Columns.port, settings.Port) .Where(MailboxServerTable.Columns.socket_type, ConvertFromEncryptionType(settings.EncryptionType)) .Where(MailboxServerTable.Columns.authentication, ConvertFromSaslMechanism(settings.AuthenticationType)) .Where(MailboxServerTable.Columns.username, accountNameMask) .Where(MailboxServerTable.Columns.is_user_data, false)); if (settingsId == 0) { settingsId = db.ExecuteScalar<int>(new SqlInsert(MailboxServerTable.name) .InColumnValue(MailboxServerTable.Columns.id, 0) .InColumnValue(MailboxServerTable.Columns.id_provider, providerId) .InColumnValue(MailboxServerTable.Columns.type, serverType) .InColumnValue(MailboxServerTable.Columns.hostname, settings.Url) .InColumnValue(MailboxServerTable.Columns.port, settings.Port) .InColumnValue(MailboxServerTable.Columns.socket_type, ConvertFromEncryptionType(settings.EncryptionType)) .InColumnValue(MailboxServerTable.Columns.authentication, ConvertFromSaslMechanism(settings.AuthenticationType)) .InColumnValue(MailboxServerTable.Columns.username, accountNameMask) .InColumnValue(MailboxServerTable.Columns.is_user_data, true) .Identity(0, 0, true)); } return settingsId; } }
/// <summary> /// Sends a RFC conform email using default .NET classes. /// </summary> /// <param name="messageToSend">The pre-configured <see cref="MailMessage" /> to send.</param> /// <param name="settings">A structure containing the settings for the server.</param> /// <returns><c>True</c> if the mail was sent, otherwise <c>false</c>.</returns> public static bool SendMail(MailMessage messageToSend, MailServerSettings settings) { return(AsyncUtil.CallSync(() => SendMailAsync(messageToSend, settings))); }
/// <summary> /// Sends a RFC conform email using default .NET classes. /// </summary> /// <param name="fromAddress">Mail-address of the sender.</param> /// <param name="toAddresses">Mail-addresses of the receivers.</param> /// <param name="subject">Subject of the mail.</param> /// <param name="body">The string for the body of the mail.</param> /// <param name="settings">A structure containing the settings for the server.</param> /// <returns><c>True</c> if the mail was sent, otherwise <c>false</c>.</returns> public static bool SendMail(string fromAddress, string[] toAddresses, string subject, string body, MailServerSettings settings) { CheckUtil.ThrowIfNullOrWhitespace(() => subject); CheckUtil.ThrowIfNullOrWhitespace(() => body); var result = false; if (!fromAddress.IsValidEmailAddress()) { throw new ArgumentException("Invalid e-mail-address of sender.", nameof(fromAddress)); } if (!toAddresses.Any()) { throw new ArgumentException("No receipient submitted!", nameof(toAddresses)); } if (toAddresses.Any(a => !a.IsValidEmailAddress())) { throw new ArgumentException("Invalid e-mail-address of on of the recipient.", nameof(toAddresses)); } // Send the mail and use credentials if given. using (var message = new MailMessage(fromAddress, toAddresses.First(), subject, body)) { if (toAddresses.Count() > 1) { // add the other receipients for (var i = 1; i < toAddresses.Count(); i++) { message.To.Add(toAddresses[i]); } } result = SendMail(message, settings); } return(result); }
/// <summary> /// Sends a RFC conform email using default .NET classes. /// </summary> /// <param name="fromAddress">Mail-address of the sender.</param> /// <param name="toAddress">Mail-address of the receiver.</param> /// <param name="subject">Subject of the mail.</param> /// <param name="body">The string for the body of the mail.</param> /// <param name="settings">A structure containing the settings for the server.</param> /// <returns><c>True</c> if the mail was sent, otherwise <c>false</c>.</returns> public static bool SendMail(string fromAddress, string toAddress, string subject, string body, MailServerSettings settings) { return(SendMail(fromAddress, new[] { toAddress }, subject, body, settings)); }
public static string Authorize(this BaseProtocolClient ingoing_mail_client, MailServerSettings settings, int wait_timeout = 5000, ILogger log = null) { if (log == null) { log = new NullLogger(); } string last_response; IAsyncResult async_res; switch (settings.EncryptionType) { case EncryptionType.SSL: log.Debug("SSL connecting to {0}", settings.Url); async_res = ingoing_mail_client.BeginConnectSsl(settings.Url, settings.Port, result => log.Debug("OnConnectSSL: completed {0}", result.IsCompleted ? "SUCCESS" : "FAIL")); if (!async_res.AsyncWaitHandle.WaitOne(wait_timeout)) { log.Warn("BeginConnectSsl: operation timeout = {0} seconds", TimeSpan.FromMilliseconds(wait_timeout).Seconds); ingoing_mail_client.EndAsyncOperation(async_res); async_res.AsyncWaitHandle.Close(); throw new TimeoutException(); } last_response = ingoing_mail_client.EndAsyncOperation(async_res); break; default: log.Debug("PLAIN connecting to {0}", settings.Url); async_res = ingoing_mail_client.BeginConnectPlain(settings.Url, settings.Port, result => log.Debug( "OnConnect: completed {0}", result .IsCompleted ? "SUCCESS" : "FAIL")); if (!async_res.AsyncWaitHandle.WaitOne(wait_timeout)) { log.Warn("BeginConnect: operation timeout = {0} seconds", TimeSpan.FromMilliseconds(wait_timeout).Seconds); ingoing_mail_client.EndAsyncOperation(async_res); async_res.AsyncWaitHandle.Close(); throw new TimeoutException(); } last_response = ingoing_mail_client.EndAsyncOperation(async_res); if (ingoing_mail_client is SmtpClient && (settings.AuthenticationType != SaslMechanism.None || settings.EncryptionType == EncryptionType.StartTLS)) { last_response = ingoing_mail_client.SendEhloHelo(); } if (settings.EncryptionType == EncryptionType.StartTLS) { log.Debug("StartTLS {0}", settings.Url); last_response = ingoing_mail_client.StartTLS(settings.Url); } break; } if (settings.AuthenticationType == SaslMechanism.Login) { log.Debug("Login as {0} with secret password", settings.AccountName); async_res = ingoing_mail_client.BeginLogin(settings.AccountName, settings.AccountPass, result => log.Debug("OnLogin: completed {0}", result.IsCompleted ? "SUCCESS" : "FAIL")); if (!async_res.AsyncWaitHandle.WaitOne(wait_timeout)) { log.Warn("BeginLogin: operation timeout = {0} seconds", TimeSpan.FromMilliseconds(wait_timeout).Seconds); ingoing_mail_client.EndAsyncOperation(async_res); async_res.AsyncWaitHandle.Close(); throw new TimeoutException(); } last_response = ingoing_mail_client.EndAsyncOperation(async_res); } else { if (ingoing_mail_client is SmtpClient && settings.AuthenticationType == SaslMechanism.None) { log.Debug("Authentication not required"); return(last_response); } log.Debug("Authenticate as {0} with secret password", settings.AccountName); async_res = ingoing_mail_client.BeginAuthenticate(settings.AccountName, settings.AccountPass, settings.AuthenticationType, result => log.Debug("OnAuthenticate: completed {0}", result.IsCompleted ? "SUCCESS" : "FAIL")); if (!async_res.AsyncWaitHandle.WaitOne(wait_timeout)) { log.Warn("BeginAuthenticate: operation timeout = {0} seconds", TimeSpan.FromMilliseconds(wait_timeout).Seconds); ingoing_mail_client.EndAsyncOperation(async_res); async_res.AsyncWaitHandle.Close(); throw new TimeoutException(); } last_response = ingoing_mail_client.EndAsyncOperation(async_res); } return(last_response); }
/// <summary> /// Sends a RFC conform email using default .NET classes. /// </summary> /// <param name="messageToSend">The pre-configured <see cref="MailMessage" /> to send.</param> /// <param name="settings">A structure containing the settings for the server.</param> /// <param name="deliveryMethod">The method for mail delivery to use.</param> /// <returns><c>True</c> if the mail was sent, otherwise <c>false</c>.</returns> public static async Task<bool> SendMailAsync(MailMessage messageToSend, MailServerSettings settings, SmtpDeliveryMethod deliveryMethod = SmtpDeliveryMethod.Network) { CheckUtil.ThrowIfNull(() => messageToSend); try { // Send the mail and use credentials if given. using (var client = new SmtpClient()) { client.Host = settings.ServerAddress; client.Port = settings.Port; client.UseDefaultCredentials = settings.UseDefaultCredentials; if (settings.UseDefaultCredentials) { client.Credentials = CredentialCache.DefaultNetworkCredentials; } else { if (!string.IsNullOrEmpty(settings.Username) && !string.IsNullOrEmpty(settings.Password)) { client.Credentials = new NetworkCredential(settings.Username, settings.Password, settings.Domain ?? string.Empty); } } client.DeliveryMethod = deliveryMethod; client.EnableSsl = settings.UseSsl; await client.SendMailAsync(messageToSend).ConfigureAwait(false); } return true; } catch (Exception ex) { var error = string.Format( CultureInfo.InvariantCulture, "Cannot send e-mail from '{0}' to '{1}' with subject '{2}': {3}", messageToSend.From, messageToSend.To, messageToSend.Subject, ex); var file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments), "mail.error"); using (var writer = File.AppendText(file)) { writer.Write(error); writer.Close(); } throw new InvalidOperationException(error, ex); } }
/// <summary> /// Sends a RFC conform email using default .NET classes. /// </summary> /// <param name="messageToSend">The pre-configured <see cref="MailMessage" /> to send.</param> /// <param name="settings">A structure containing the settings for the server.</param> /// <param name="deliveryMethod">The method for mail delivery to use.</param> /// <returns><c>True</c> if the mail was sent, otherwise <c>false</c>.</returns> public static bool SendMail(MailMessage messageToSend, MailServerSettings settings, SmtpDeliveryMethod deliveryMethod = SmtpDeliveryMethod.Network) { return SendMailAsync(messageToSend, settings, deliveryMethod).Result; }
/// <summary> /// Sends a RFC conform email using default .NET classes. /// </summary> /// <param name="fromAddress">Mail-address of the sender.</param> /// <param name="toAddresses">Mail-addresses of the receivers.</param> /// <param name="subject">Subject of the mail.</param> /// <param name="body">The string for the body of the mail.</param> /// <param name="settings">A structure containing the settings for the server.</param> /// <param name="deliveryMethod">The method for mail delivery to use.</param> /// <returns><c>True</c> if the mail was sent, otherwise <c>false</c>.</returns> public static bool SendMail(string fromAddress, string[] toAddresses, string subject, string body, MailServerSettings settings, SmtpDeliveryMethod deliveryMethod = SmtpDeliveryMethod.Network) { CheckUtil.ThrowIfNullOrWhitespace(() => subject); CheckUtil.ThrowIfNullOrWhitespace(() => body); var result = false; if (!fromAddress.IsValidEmailAddress()) { throw new ArgumentException("Invalid e-mail-address of sender.", nameof(fromAddress)); } if (!toAddresses.Any()) { throw new ArgumentException("No receipient submitted!", nameof(toAddresses)); } if (toAddresses.Any(a => !a.IsValidEmailAddress())) { throw new ArgumentException("Invalid e-mail-address of on of the recipient.", nameof(toAddresses)); } // Send the mail and use credentials if given. using (var message = new MailMessage(fromAddress, toAddresses.First(), subject, body)) { if (toAddresses.Count() > 1) { // add the other receipients for (var i = 1; i < toAddresses.Count(); i++) { message.To.Add(toAddresses[i]); } } result = SendMail(message, settings, deliveryMethod); } return result; }
/// <summary> /// Sends a RFC conform email using default .NET classes. /// </summary> /// <param name="fromAddress">Mail-address of the sender.</param> /// <param name="toAddress">Mail-address of the receiver.</param> /// <param name="subject">Subject of the mail.</param> /// <param name="body">The string for the body of the mail.</param> /// <param name="settings">A structure containing the settings for the server.</param> /// <param name="deliveryMethod">The method for mail delivery to use.</param> /// <returns><c>True</c> if the mail was sent, otherwise <c>false</c>.</returns> public static bool SendMail(string fromAddress, string toAddress, string subject, string body, MailServerSettings settings, SmtpDeliveryMethod deliveryMethod = SmtpDeliveryMethod.Network) { return SendMail(fromAddress, new[] { toAddress }, subject, body, settings, deliveryMethod); }