public async Task SendEmailAsync(Feedback review) { var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress(_settings.CompanyName, _settings.UserName)); emailMessage.To.Add(new MailboxAddress(_settings.Recipient)); emailMessage.Subject = _settings.Subject; emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Text) { Text = review.Text }; try { using (var client = new MailKit.Net.Smtp.SmtpClient()) { await client.ConnectAsync(_settings.Server, _settings.Port, _settings.UseSSL); await client.AuthenticateAsync(_settings.UserName, _settings.Password); await client.SendAsync(emailMessage); await client.DisconnectAsync(true); } } catch (Exception e) { _logger.LogError(e, "Error while trying to send email."); } }
public static async Task TestConnectionAsync(this SmtpServer server) { if (string.IsNullOrEmpty(server.Host)) { throw new SmtpException("Host is required"); } else if (server.Port is <= 0 or >= 65536) { throw new SmtpException("Port value is invalid"); } using (var client = new SmtpClient()) { if (server.TlsEnabled) { await client.ConnectAsync(server.Host, server.Port, SecureSocketOptions.StartTlsWhenAvailable); } else { await client.ConnectAsync(server.Host, server.Port); } if (!string.IsNullOrEmpty(server.Username)) { await client.AuthenticateAsync(server.Username, server.Password); } await client.DisconnectAsync(true); } }
/// <summary> /// Отправка сообщения на Email /// </summary> private async Task SendMessage(string recipientEmail, string subjectMsg, string bodyMsg) { var emailMessage = new MimeMessage { From = { new MailboxAddress("Support GameKeyStore", smtpConfig.SenderEmail) }, To = { new MailboxAddress("", recipientEmail) }, ReplyTo = { new MailboxAddress("", smtpConfig.SenderEmail) }, Subject = subjectMsg, Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = bodyMsg } }; using (var client = new SmtpClient()) { await client.ConnectAsync(smtpConfig.Host, smtpConfig.Port, true); await client.AuthenticateAsync(smtpConfig.SenderEmail, smtpConfig.SenderPassword); await client.SendAsync(emailMessage); await client.DisconnectAsync(true); } }
public override async Task StartAsync(CancellationToken cancellationToken) { var message = new MimeMessage(); message.To.Add(new MailboxAddress("talha", "*****@*****.**")); message.From.Add(new MailboxAddress("talha", "*****@*****.**")); message.Subject = "Hi"; message.Body = new TextPart(TextFormat.Html) { Text = "Email for testing" }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { await client.ConnectAsync("smtp-mail.outlook.com", 587, SecureSocketOptions.Auto); client.AuthenticationMechanisms.Remove("XOAUTH2"); await client.AuthenticateAsync("*****@*****.**", "Password"); await client.SendAsync(message); await client.DisconnectAsync(true); } }
public async Task SendAsync(EmailMessage msg) { var message = new MimeMessage(); message.To.AddRange(msg.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address))); message.From.AddRange(msg.FromAddresses.Select(x => new MailboxAddress(x.Name, x.Address))); message.Subject = msg.Subject; message.Body = new TextPart("plain") { Text = msg.Content }; try { using (var client = new MailKit.Net.Smtp.SmtpClient()) { await client.ConnectAsync(_eConfig.SmtpServer, _eConfig.SmtpPort, true); await client.AuthenticateAsync(_eConfig.SmtpUsername, _eConfig.SmtpPassword); await client.SendAsync(message); await client.DisconnectAsync(true); } } catch (Exception ex) { // TODO: handle exception throw new InvalidOperationException(ex.Message); } }
private async void SendEmail(MimeMessage message) { var SmtpServer = _config.GetSection("EmailConfig.SmtpServer").Value; var SmtpPort = Convert.ToInt32(_config.GetSection("EmailConfig.SmtpPort").Value); var SmtpUsername = _config.GetSection("EmailConfig.SmtpUsername").Value; var SmtpPassword = _config.GetSection("EmailConfig.SmtpPassword").Value; try { using (var smtp = new MailKit.Net.Smtp.SmtpClient()) { await smtp.ConnectAsync(SmtpServer, SmtpPort); var isSecure = smtp.IsSecure; await smtp.AuthenticateAsync(SmtpUsername, SmtpPassword); await smtp.SendAsync(message); //await smtp.DisconnectAsync(true); } ; } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public async Task SendEmailAsync(string email, string subject, string message) { _ = new MailAddress(email); if (string.IsNullOrEmpty(subject) && string.IsNullOrEmpty(message)) { subject = "BCB notification"; message = "This message is sent for unmanaged purpose"; } var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress("Black Caviar Bank administration", "*****@*****.**")); emailMessage.To.Add(new MailboxAddress("", email)); emailMessage.Subject = subject; emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = message }; using var client = new MailKit.Net.Smtp.SmtpClient(); await client.ConnectAsync("smtp.gmail.com", 465, true); await client.AuthenticateAsync("*****@*****.**", "fakerfaker24"); await client.SendAsync(emailMessage); await client.DisconnectAsync(true); }
public Task SendEmailAsync(MimeMessage msg) { // Plug in your email service here to send an email. // Pull API Key from Config var apiKey = _configuration["AppSettings:SendGridSMTPAPIKey"]; var username = _configuration["AppSettings:SendGridUserName"]; var password = _configuration["AppSettigns:SendGridPassword"]; NetworkCredential credential = new NetworkCredential(username, password); // Create transport and send message try { using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.ConnectAsync("smtp.sendgrid.net", Convert.ToInt32(587)); client.AuthenticateAsync(credential); client.SendAsync(msg); client.DisconnectAsync(true); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(Task.FromResult(0)); }
public async Task SendEmailAsync(string email, string subject, string message) { try { var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress(ec.FromName, ec.FromAddress)); emailMessage.To.Add(new MailboxAddress("", email)); emailMessage.Subject = subject; emailMessage.Body = new TextPart(TextFormat.Html) { Text = message }; using (var client = new SmtpClient()) { client.LocalDomain = ec.LocalDomain; await client.ConnectAsync(ec.MailServerAddress, Convert.ToInt32(ec.MailServerPort), SecureSocketOptions.Auto).ConfigureAwait(false); await client.AuthenticateAsync(new NetworkCredential(ec.UserId, ec.UserPassword)); await client.SendAsync(emailMessage).ConfigureAwait(false); await client.DisconnectAsync(true).ConfigureAwait(false); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public async Task <bool> SendEmail(UserDTO model, string message) { try { var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress("Innoflow-admin", "*****@*****.**")); emailMessage.To.Add(new MailboxAddress("", model.Email)); emailMessage.Subject = "Подтвердите свою почту"; emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = message }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Timeout = (int)TimeSpan.FromSeconds(5).TotalMilliseconds; await client.ConnectAsync("smtp.gmail.com", 587, false); await client.AuthenticateAsync("*****@*****.**", "kctoszrouldiouuo"); await client.SendAsync(emailMessage); await client.DisconnectAsync(true); } } catch (Exception e) { Console.WriteLine("Ошибка при отправке почты" + e.Message); return(false); } return(true); }
private static async Task SendSubscription(MailKey mailKey, string title, string context, string mail) { var messageToSend = new MimeMessage { Sender = new MailboxAddress("lindexi", "*****@*****.**"), Subject = title, Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = context, }, To = { new MailboxAddress(mail) } }; using (var smtp = new MailKit.Net.Smtp.SmtpClient()) { await smtp.ConnectAsync("smtp-mail.outlook.com", port : 587, MailKit.Security.SecureSocketOptions.StartTls); await smtp.AuthenticateAsync(mailKey.Name, mailKey.Key); await smtp.SendAsync(messageToSend); await smtp.DisconnectAsync(true); } }
public async Task <Result> Send(EmailMessage message, CancellationToken token) { try { var options = _options.Value; var mimeMessage = Parse(message); using (var emailClient = new MailKit.Net.Smtp.SmtpClient()) { emailClient.Connect(options.Server, options.Port, true); //Remove any OAuth functionality as we won't be using it. emailClient.AuthenticationMechanisms.Remove("XOAUTH2"); await emailClient.AuthenticateAsync(options.Username, options.Password, token); await emailClient.SendAsync(mimeMessage, token); await emailClient.DisconnectAsync(true, token); } _logger.LogInformation($"sent e-mail to [{string.Join(", ", message.To)}], content: {message.Body.TruncateWithEllipsis(1000)}"); return(Result.Success()); } catch (Exception ex) when(IsKnown(ex)) { _logger.LogWarning($"failed to send e-mail to [{string.Join(", ", message.To)}], exception: {ex.ToString()}, content: {message.Body.TruncateWithEllipsis(1000)}"); return(Result.Failure("Failed to send e-mail")); } }
private async Task SendEmailAsync(Action <InternetAddressList> action, string subject, string content) { var settings = _settingsManager.GetSettings <EmailSettings>(); if (!settings.Enabled) { return; } var site = _settingsManager.GetSettings <SiteSettings>(); var message = new MimeMessage(); message.From.Add(new MailboxAddress(site.SiteName, settings.SmtpUserName)); action(message.To); message.Subject = ReplaceKeyWords(site, subject); var html = new TextPart("html"); html.Text = ReplaceKeyWords(site, content); message.Body = html; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.AuthenticationMechanisms.Remove("XOAUTH2"); await client.ConnectAsync(settings.SmtpServer, settings.SmtpPort, settings.UseSsl); await client.AuthenticateAsync(settings.SmtpUserName, settings.SmtpPassword); await client.SendAsync(message); await client.DisconnectAsync(true); } }
public MimeKitSmtpClientBuilder SetUpConnection(string userName, string password) { _connectTask = _client.ConnectAsync("smtp.gmail.com", 587, false); _authenticateTask = _client.AuthenticateAsync(userName, password); return(this); }
public async Task SendEmail(string receiverEmail, string subject, string content) { try { var mimeMessage = new MimeMessage(); mimeMessage.From.Add(new MailboxAddress("Self", "*****@*****.**")); mimeMessage.To.Add(new MailboxAddress("Self", receiverEmail)); mimeMessage.Subject = subject; mimeMessage.Body = new TextPart(MimeKit.Text.TextFormat.Text) { Text = content }; using (MailKit.Net.Smtp.SmtpClient smtpClient = new MailKit.Net.Smtp.SmtpClient()) { await smtpClient.ConnectAsync("smtp.gmail.com", 587); await smtpClient.AuthenticateAsync("*****@*****.**", "adoojohn"); await smtpClient.SendAsync(mimeMessage); await smtpClient.DisconnectAsync(true); } } catch (Exception ex) { int i = 5; } }
private async Task <SmtpClient> CreateConnectedSmtpClientAsync(CancellationToken cancellationToken) { var smtpClient = new SmtpClient(); try { await smtpClient.ConnectAsync( this._mailSettings.Host, this._mailSettings.Port, this._mailSettings.EnableSSL, cancellationToken ); if (this._mailSettings.HasAuthenticationInfo) { await smtpClient.AuthenticateAsync( this._mailSettings.UserName, this._mailSettings.Password, cancellationToken ); } return(smtpClient); } catch (Exception ex) { this._logger.LogError(ex, $"Unable to create SMTP client for {this._mailSettings.Host}:{this._mailSettings.Port}"); smtpClient?.Dispose(); throw new MailServiceException($"Unable to create SMTP client for host {this._mailSettings.Host}", ex); } }
public async Task SendMail(MailBody mailBody, MailServerConfig mailServer, Action messageSentAction = null) { if (mailBody == null) { throw new ArgumentException("参数为null"); } var mimeMessage = new MimeMessage(); mimeMessage.Subject = mailBody.Subject; mimeMessage.From.Add(new MailboxAddress(mailBody.Sender, mailBody.SenderAddress)); mimeMessage.Body = new TextPart(mailBody.BodyType) { Text = mailBody.Body }; mimeMessage.To.Add(new MailboxAddress(mailBody.Revicer, mailBody.RevicerAddress)); using (var smtp = new MailKit.Net.Smtp.SmtpClient()) { if (messageSentAction != null) { smtp.MessageSent += (sender, e) => { messageSentAction(); }; } smtp.ServerCertificateValidationCallback = (s, c, h, e) => true; await smtp.ConnectAsync(mailServer.Server, mailServer.Port, SecureSocketOptions.SslOnConnect); await smtp.AuthenticateAsync(mailServer.Account, mailServer.Password); await smtp.SendAsync(mimeMessage); await smtp.DisconnectAsync(true); } }
/// <summary> /// Sends an email /// </summary> /// <param name="emailAccount">Email account to use</param> /// <param name="subject">Subject</param> /// <param name="body">Body</param> /// <param name="fromAddress">From address</param> /// <param name="fromName">From display name</param> /// <param name="toAddress">To address</param> /// <param name="toName">To display name</param> public virtual async Task SendEmail(MailOptions emailAccount, string subject, string body, string fromAddress, string fromName, string toAddress, string toName) { var message = new MimeMessage(); //from, to, reply to message.From.Add(new MailboxAddress(fromName, fromAddress)); message.To.Add(new MailboxAddress(toName, toAddress)); //subject message.Subject = subject; //content var builder = new BodyBuilder { HtmlBody = body }; message.Body = builder.ToMessageBody(); //send email using var smtpClient = new MailKit.Net.Smtp.SmtpClient(); //smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => emailAccount.UseServerCertificateValidation; await smtpClient.ConnectAsync(emailAccount.Server, emailAccount.Port, SecureSocketOptions.Auto); await smtpClient.AuthenticateAsync(emailAccount.Account, emailAccount.Password); await smtpClient.SendAsync(message); await smtpClient.DisconnectAsync(true); }
/// <summary> /// 发送电子邮件。 /// </summary> /// <param name="settings">网站配置。</param> /// <param name="message">消息实例。</param> /// <returns>返回发送任务。</returns> protected virtual async Task SendAsync(EmailSettings settings, Email message) { using (var client = new MailKit.Net.Smtp.SmtpClient()) { await client.ConnectAsync(settings.SmtpServer, settings.SmtpPort, settings.UseSsl); await client.AuthenticateAsync(settings.SmtpUserName, settings.SmtpPassword); var mail = new MimeMessage(); mail.From.Add(new MailboxAddress(settings.SmtpUserName)); mail.To.Add(new MailboxAddress(message.To)); mail.Subject = message.Title; var html = new TextPart("Html") { Text = message.Content }; var multipart = await InitAsync(mail, message); if (multipart != null) { multipart.Insert(0, html); mail.Body = multipart; } else { mail.Body = html; } await client.SendAsync(mail); } }
private async Task <MailKit.IMailTransport> CreateTransport() { SecureSocketOptions secureSocketOptions = SecureSocketOptions.SslOnConnect; MailKit.Net.Smtp.SmtpClient smtpClient = new MailKit.Net.Smtp.SmtpClient(); smtpClient.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; try { await smtpClient.ConnectAsync(_Settings.SmtpMailServer, _Settings.SmtpPort, secureSocketOptions); var authMech = smtpClient.AuthenticationMechanisms; if (smtpClient.IsConnected) { await smtpClient.AuthenticateAsync(_Settings.SenderLogin, _Settings.SenderPassword); } if (!smtpClient.IsAuthenticated) { return(smtpClient); } } catch (AggregateException e) { _Logger?.LogError(e, e.Message); throw; } return(smtpClient); }
public async Task <SmtpClient> GetSmtpClient() { try { SmtpClient client = new SmtpClient(); await client.ConnectAsync(Smtp.Server, Smtp.Port, Smtp.UseSsl); await client.AuthenticateAsync(Address, _password); return(client); } catch (SocketException ex) { string message = "Соединение с почтовым сервером не установлено. "; if (ex.ErrorCode == 11001) { message += "Проверьте подключение к интернету."; } else { message += ex.Message; } throw new Exception(message); } catch { throw new Exception("Логин или пароль неверны."); } }
private async Task SendAsync(MimeMessage mailMessage) { using (var client = new SmtpClient()) { try { if (_env.IsDevelopment()) { await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.Port, MailKit.Security.SecureSocketOptions.SslOnConnect); } else { await client.ConnectAsync(_emailConfig.SmtpServer); } client.AuthenticationMechanisms.Remove("XOAUTH2"); await client.AuthenticateAsync(_emailConfig.UserName, _emailConfig.Password); await client.SendAsync(mailMessage); } catch (Exception ex) { //log an error message or throw an exception, or both. throw; } finally { await client.DisconnectAsync(true); client.Dispose(); } } }
private async static Task MailKiteSmtp() { var smtp = new SmtpClientMailKit(); // await smtp.ConnectAsync("smtp.gmail.com", 587, true); await smtp.ConnectAsync("smtp.gmail.com", 465, true); await smtp.AuthenticateAsync("*****@*****.**", "qqwwee11!!"); if (smtp.IsAuthenticated) { Console.WriteLine("OK"); } var message = new MimeMessage(); message.From.Add(new MailboxAddress("Dasha", "*****@*****.**")); message.To.Add(new MailboxAddress("Bohdan", "*****@*****.**")); message.Subject = "How you doin?"; message.Body = new TextPart("plain") { Text = @"Please work" }; await smtp.SendAsync(message); }
public async Task SendMessageAsync(MMailMessage message) { var smtpClient = new MailKit.Net.Smtp.SmtpClient(); if (options.IgnoreSSLError) { smtpClient.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true; } SecureSocketOptions secOpts = SecureSocketOptions.Auto; if (!options.UseSSL) { secOpts = SecureSocketOptions.None; } await smtpClient.ConnectAsync(options.SMTPServer, options.SMTPServerPort, secOpts); smtpClient.AuthenticationMechanisms.Remove("XOAUTH2"); if (options.Credentials != null) { await smtpClient.AuthenticateAsync(options.Credentials); } await smtpClient.SendAsync(message); await smtpClient.DisconnectAsync(true); }
public async Task <string> SendEmailAsync(MailContent content) { MimeMessage email = new MimeMessage(); // Email from email.From.Add(new MailboxAddress(_config.DisplayName, _config.Mail)); // Mail to email.To.Add(new MailboxAddress(content.To, content.To)); //Subject email.Subject = content.Subject; //Body var bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = content.Body; if (content.Attachments != null) { for (var i = 0; i < content.Attachments.Length; i++) { byte[] data = File.ReadAllBytes(content.Attachments[i]); bodyBuilder.Attachments.Add(Path.GetFileName(content.Attachments[i]), data); } // var multipart = new Multipart("mixed"); // multipart.Add(bodyContent); // foreach (MimePart item in content.Attachments) // { // using FileStream fs = File.OpenRead(item.FileName); // item.Content = new MimeContent(fs, ContentEncoding.Default); // item.ContentDisposition = new ContentDisposition(ContentDisposition.Attachment); // item.ContentTransferEncoding = ContentEncoding.Base64; // item.FileName = Path.GetFileName(item.FileName); // multipart.Add(item); // } // email.Body = multipart; } email.Body = bodyBuilder.ToMessageBody(); //SMTP using var smtp = new MailKit.Net.Smtp.SmtpClient(); try { await smtp.ConnectAsync(_config.SmtpHost, _config.Port, MailKit.Security.SecureSocketOptions.StartTls); await smtp.AuthenticateAsync(_config.Mail, _config.Pwd); await smtp.SendAsync(email); } catch (Exception ex) { return("Send email false: " + ex.Message); } return("SEND MAIL SUCCESSFUL" + DateTime.Now); }
public static async Task <SpgMailClient> Create(string username, string password, System.Threading.CancellationToken token = default) { var client = new MailKit.Net.Smtp.SmtpClient(); await client.ConnectAsync(SmtpServer, SmtpPort, MailKit.Security.SecureSocketOptions.StartTls, token); await client.AuthenticateAsync(username, password, token); return(new SpgMailClient(client)); }
private async Task SendMailMessage(AppEventModel message) { var config = this._configuration.GetSection("SiteSettings:MailConfig"); var mailServer = config.GetValue <String>("SMTPServer"); var mailPort = config.GetValue <int>("SMTPPort"); var mailSender = config.GetValue <String>("Sender"); var mailSenderPassword = config.GetValue <string>("SenderPassword"); var mailReceiver = config.GetValue <string>("Receiver"); bool useSSL = config.GetValue <bool>("UseSsl"); var mailMessage = new MimeMessage(); var sender = new MailboxAddress("Notifier", mailSender); logger.LogInformation(mailServer); logger.LogInformation(mailPort.ToString()); logger.LogInformation(mailSender); logger.LogInformation(mailReceiver); mailMessage.Sender = sender; mailMessage.Subject = message.EventTitle; mailMessage.From.Add(sender); StringBuilder builder = new StringBuilder(); builder.AppendLine("<div>"); builder.AppendLine(string.Format("<h1>{0}</h1>", message.EventTitle)); builder.AppendLine(string.Format("<h2>{0}</h2>", message.EventOwner)); builder.AppendLine(string.Format("<p>{0}</p>", message.EventDetails)); builder.AppendLine("</div>"); mailMessage.To.Add(new MailboxAddress("Support", mailReceiver)); mailMessage.Body = new TextPart(TextFormat.Html) { Text = builder.ToString() }; using (var mailClient = new MailKit.Net.Smtp.SmtpClient()) { mailClient.MessageSent += (sender, args) => { logger.LogInformation("mail sent by :" + sender); }; if (useSSL) { mailClient.ServerCertificateValidationCallback = (s, c, h, e) => true; await mailClient.ConnectAsync(mailServer, mailPort, SecureSocketOptions.Auto); } else { await mailClient.ConnectAsync(mailServer, mailPort, SecureSocketOptions.None); } await mailClient.AuthenticateAsync(mailSender, mailSenderPassword); await mailClient.SendAsync(mailMessage); await mailClient.DisconnectAsync(true); } }
/// <summary> /// メール送信試験 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void SendTestButton_Click(object sender, EventArgs e) { try { var message = new MimeKit.MimeMessage(); message.From.Add(new MimeKit.MailboxAddress(SenderNameTextBox.Text, SenderAddressTextBox.Text)); string[] name = ReceiverNameTextBox.Text.Replace(",", ";").Split(';'); string[] addresses = ReceiverAddressTextBox.Text.Replace(",", ";").Split(';'); try { for (int i = 0; i < addresses.Length; i++) { message.To.Add(new MimeKit.MailboxAddress(name[i].Trim(), addresses[i].Trim())); } } catch (Exception) { this.ShowErrorDialog("宛先・送信先エラー", "宛先又は送信先が不正です。"); return; } message.Subject = MailTitleTextBox.Text; var textPart = new MimeKit.TextPart(MimeKit.Text.TextFormat.Plain); textPart.Text = MailTextBox.Text; message.Body = textPart; using (var client = new MailKit.Net.Smtp.SmtpClient()) { try { await client.ConnectAsync(MailHostTextBox.Text, int.Parse(PortNoTextBox.Text)); if (!string.IsNullOrEmpty(UserNameTextBox.Text) && !string.IsNullOrEmpty(PasswordTextBox.Text)) { await client.AuthenticateAsync(UserNameTextBox.Text, PasswordTextBox.Text); } await client.SendAsync(message); await client.DisconnectAsync(true); this.ShowDialog("送信成功", "メール送信に成功しました!!"); } catch (Exception ex) { this.ShowErrorDialog("メール送信失敗", ex.Message); Console.WriteLine(ex.Message); } } } catch (Exception ex) { throw Program.ThrowException(ex); } }
public async Task SendEmailAsync(Email emailData, SmtpConfig config) { try { var mainUrl = Path.Combine(_env.ContentRootPath, "wwwroot"); var email = new MimeMessage(); email.From.Add(new MailboxAddress(emailData.FromDisplayName, emailData.FromEmailAddress)); email.To.Add(new MailboxAddress(emailData.ToName, emailData.ToEmailAddress)); email.Subject = emailData.Subject; var content = string.Empty; /* var urlMail = Path.Combine(mainUrl, "emailResources", "emailTemplate.html"); * * var objReader = new StreamReader(urlMail); * content = objReader.ReadToEnd(); * objReader.Close(); * * content = Regex.Replace(content, "{BoydText}", emailData.Message);*/ var body = new BodyBuilder { HtmlBody = emailData.Message }; if (emailData.Array != null) { body.Attachments.Add("Proposal.pdf", emailData.Array, new ContentType("application", "pdf")); } email.Body = body.ToMessageBody(); using var client = new MailKit.Net.Smtp.SmtpClient(); client.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; client.AuthenticationMechanisms.Remove("XOAUTH2"); // Start of provider specific settings await client.ConnectAsync(config.SmtpHost, config.Port, false).ConfigureAwait(false); await client.AuthenticateAsync(config.UserName, config.Password).ConfigureAwait(false); // End of provider specific settings await client.SendAsync(email).ConfigureAwait(false); await client.DisconnectAsync(true).ConfigureAwait(false); } catch (Exception ex) { var extraData = new { smtpConfig = config, dataEmail = emailData }; _logLogic.InsertLog(new Log("Enviar email", ex.Message, extraData)); throw ex; } }
public async Task DoSending(MimeMessage mailMessage) { using (var client = new MailKit.Net.Smtp.SmtpClient()) { await client.ConnectAsync("smtp.gmail.com", 587, SecureSocketOptions.StartTlsWhenAvailable); await client.AuthenticateAsync("*****@*****.**", "GaviSpe64!"); await client.SendAsync(mailMessage); await client.DisconnectAsync(true); } }