public async Task SendEmailAsync(string email, string subject, string htmlMessage) { var message = new MimeMessage { Sender = new MailboxAddress(mailSettings.DisplayName, mailSettings.Mail) }; message.From.Add(new MailboxAddress(mailSettings.DisplayName, mailSettings.Mail)); message.To.Add(MailboxAddress.Parse(email)); message.Subject = subject; var builder = new BodyBuilder { HtmlBody = htmlMessage }; message.Body = builder.ToMessageBody(); // dùng SmtpClient của MailKit using var smtp = new MailKit.Net.Smtp.SmtpClient(); try { smtp.Connect(mailSettings.Host, mailSettings.Port, SecureSocketOptions.StartTls); smtp.Authenticate(mailSettings.Mail, mailSettings.Password); await smtp.SendAsync(message); } catch (Exception ex) { // Gửi mail thất bại, nội dung email sẽ lưu vào thư mục mailssave System.IO.Directory.CreateDirectory("mailssave"); var emailsavefile = string.Format(@"mailssave/{0}.eml", Guid.NewGuid()); await message.WriteToAsync(emailsavefile); logger.LogInformation("Lỗi gửi mail, lưu tại - " + emailsavefile); logger.LogError(ex.Message); } smtp.Disconnect(true); logger.LogInformation("send mail to: " + email); }
public static async Task SendMailAsync(String toEmail, String toName, String subject, String bodyText) { var from = new MailboxAddress("Vivek Khandelwal", "*****@*****.**"); var messageToSend = new MimeMessage { Sender = from, Subject = subject, }; messageToSend.From.Add(from); if (String.IsNullOrWhiteSpace(toName)) { messageToSend.To.Add(new MailboxAddress(toEmail)); } else { messageToSend.To.Add(new MailboxAddress(toName, toEmail)); } messageToSend.Body = new TextPart(TextFormat.Html) { Text = bodyText }; String fromUsername = from.Address; string fromPassword = ""; // To be updated using (var smtp = new MailKit.Net.Smtp.SmtpClient()) { smtp.ServerCertificateValidationCallback = (s, c, h, e) => true; await smtp.ConnectAsync("smtp.gmail.com", 587, SecureSocketOptions.StartTls); await smtp.AuthenticateAsync(fromUsername, fromPassword); await smtp.SendAsync(messageToSend); await smtp.DisconnectAsync(true); } }
protected override async Task Send(NotificationMessage model, EmailNotificationSettings settings) { try { var body = new BodyBuilder { HtmlBody = model.Message, TextBody = model.Other["PlainTextBody"] }; var message = new MimeMessage { Body = body.ToMessageBody(), Subject = model.Subject }; message.From.Add(new MailboxAddress(settings.EmailSender, settings.EmailSender)); message.To.Add(new MailboxAddress(model.To, model.To)); using (var client = new SmtpClient()) { client.Connect(settings.EmailHost, settings.EmailPort); // Let MailKit figure out the correct SecureSocketOptions. // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); if (settings.Authentication) { client.Authenticate(settings.EmailUsername, settings.EmailPassword); } Log.Info("sending message to {0} \r\n from: {1}\r\n Are we authenticated: {2}", message.To, message.From, client.IsAuthenticated); await client.SendAsync(message); await client.DisconnectAsync(true); } } catch (Exception e) { Log.Error(e); throw new InvalidOperationException(e.Message); } }
public async Task SendEmailAsync(MimeMessage message) { //Send the message via O365 using (var client = new MailKit.Net.Smtp.SmtpClient()) { //client.LocalDomain = "smtp.gmail.com" ; await client.ConnectAsync(_mailSettings.Server, _mailSettings.Port, false); client.AuthenticationMechanisms.Remove("XOAUTH2"); await client.AuthenticateAsync( _mailSettings.UserName, _mailSettings.Password ); await client.SendAsync(message); await client.DisconnectAsync(true); } }
private MailSendResult SendViaMailKit(MimeMessage message) { MailSendResult sendResult = new MailSendResult(); if (!message.From.Any()) { message.From.Add(new MailboxAddress(_settingsService.GetSettings <string>("SystemEmailSenderName"), _settingsService.GetSettings <string>("SystemEmailAddress"))); } if (AppSettingsHelper.EmailBlindCarbonCopyEnabled) { string bcc = AppSettingsHelper.EmailBlindCarbonCopyAddress; message.Bcc.Add(new MailboxAddress(bcc)); } string host = _settingsService.GetSettings <string>("EmailSmtpUrl"); int port = _settingsService.GetSettings <int>("EmailSmtpPort"); SecureSocketOptions socketSecurityOption = _settingsService.GetSettings <bool>("SmtpSslEnabled") ? SecureSocketOptions.SslOnConnect : SecureSocketOptions.Auto; string username = _settingsService.GetSettings <string>("EmailLogin"); string password = _settingsService.GetSettings <string>("EmailPassword"); try { Task.Run(async() => { using (var smtp = new MailKit.Net.Smtp.SmtpClient()) { await smtp.ConnectAsync(host, port, socketSecurityOption); await smtp.AuthenticateAsync(username, password); await smtp.SendAsync(message); //отправка sendResult.Success = true; await smtp.DisconnectAsync(true); } }).Wait(); } catch (Exception e) { _logService.LogError(e); sendResult.Success = false; sendResult.ErrorMsg = e.Message; } return(sendResult); }
public static async Task <bool> SendEmail(string address, string title, string text) { MimeMessage message = new MimeMessage(); message.From.Add(new MailboxAddress("sender", "*****@*****.**")); message.To.Add(new MailboxAddress("reciever", address)); message.Subject = title; var bodyBuilder = new BodyBuilder { HtmlBody = string.Format(text) }; message.Body = bodyBuilder.ToMessageBody(); using (var client = new MailKit.Net.Smtp.SmtpClient()) { try { // Accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; await client.ConnectAsync("", 465, true); // Authenticate email with server await client.AuthenticateAsync("", ""); // Send message to receiver await client.SendAsync(message); // Disconect to unlock unnecessary resources await client.DisconnectAsync(true); return(true); } catch (Exception) { return(false); } } }
public async Task <string> Handle(SendEmailCommand request, CancellationToken cancellationToken) { var user = _repository.GetUsersAsync(). FirstOrDefaultAsync(x => x.Email == request.EmailAddress, cancellationToken: cancellationToken).Result; var guid = _repository.AddUserEmailDataConfirmation(request.EmailAddress); var message = new MimeMessage(); try { if (user == null) { return("Bad"); } message.From.Add(new MailboxAddress("Todo List", SendEmailCommand.EmailClientName)); message.To.Add(new MailboxAddress(user.FirstName, request.EmailAddress)); message.Subject = "Message from Todo List"; message.Body = new BodyBuilder() { HtmlBody = $"<a href=\"https://localhost:5001/ConfirmationPassword/{guid.Result}\" style\"color: green;\">" + $"<div style=\"color: green;\">Чтобы поменять пароль на другой, пройдите по этой ссылке</div></div></a>" }.ToMessageBody(); using var client = new MailKit.Net.Smtp.SmtpClient(); await client.ConnectAsync("smtp.gmail.com", 465, true, cancellationToken); await client.AuthenticateAsync(SendEmailCommand.EmailClientName, SendEmailCommand.EmailClientPassword, cancellationToken); await client.SendAsync(message, cancellationToken); await client.DisconnectAsync(true, cancellationToken); return(""); } catch (Exception e) { return(e.GetBaseException().Message); } }
public async Task SendMail(MailContent mailContent) { var email = new MimeMessage(); email.Sender = new MailboxAddress(_mailSettings.DisplayName, _mailSettings.Mail); email.From.Add(new MailboxAddress(_mailSettings.DisplayName, _mailSettings.Mail)); email.To.Add(MailboxAddress.Parse(mailContent.To)); email.Subject = mailContent.Subject; var coppies = new List <MailboxAddress>(); if (mailContent.CCTos != null) { foreach (var ccTo in mailContent.CCTos) { coppies.Add(new MailboxAddress(_mailSettings.DisplayName, ccTo)); } } email.Cc.AddRange(coppies); var builder = new BodyBuilder(); builder.HtmlBody = mailContent.Body; email.Body = builder.ToMessageBody(); var smtp = new MailKit.Net.Smtp.SmtpClient(); try { smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls); smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password); await smtp.SendAsync(email); } catch (Exception ex) { // Gửi mail thất bại, nội dung email sẽ lưu vào thư mục mailssave System.IO.Directory.CreateDirectory("mailssave"); var emailsavefile = string.Format(@"mailssave/{0}.eml", Guid.NewGuid()); email.WriteTo(emailsavefile); } smtp.Disconnect(true); }
public async void SendEmailAlert() { try { var smtpClient = new MailKit.Net.Smtp.SmtpClient(); await smtpClient.ConnectAsync(this.smtpUrl, this.smtpPort, true); // this option is only needed if server requires it // the port will also depend on the provider/hosting provider await smtpClient.AuthenticateAsync(this.username, this.password); await smtpClient.SendAsync(this.message); await smtpClient.DisconnectAsync(true); } catch (Exception error) { Console.WriteLine("An error occurred with the email \n {0}", error.Message); } }
public async Task EmailRandomNames(Range range, string email = "*****@*****.**") { var message = new MimeMessage(); message.From.Add(new MailboxAddress("Generator", "*****@*****.**")); message.To.Add(new MailboxAddress("", email)); message.Subject = "Here are your random names!"; message.Body = new TextPart("plain") { Text = string.Join(Environment.NewLine, range.Of(Name.FullName)) }; using (var mailClient = new MailKit.Net.Smtp.SmtpClient()) { await mailClient.ConnectAsync(MAIL_HOST, MAIL_PORT, SecureSocketOptions.None); await mailClient.SendAsync(message); await mailClient.DisconnectAsync(true); } }
public async Task SendAsync(SendMailCommand mailDto, ProviderSettings settings) { var message = mailDto.ToMimeMessage(settings.Smtp); if (!_smtpClient.IsAuthenticated || !_smtpClient.IsConnected) { _smtpClient.LocalDomain = settings.Smtp.LocalDomain; await _smtpClient.ConnectAsync(settings.Smtp.Host, settings.Smtp.Port, settings.Smtp.SecureSocketOptions).ConfigureAwait(false); if (settings.Smtp.User != null && settings.Smtp.Password != null) { _smtpClient.Authenticate(settings.Smtp.User, settings.Smtp.Password); } } await _smtpClient.SendAsync(message).ConfigureAwait(false); if (!settings.KeepConnection) { await _smtpClient.DisconnectAsync(true).ConfigureAwait(false); } }
public async Task SendOrderConfirmationEmailAsync(Domain.Models.Order order) { _mail.To.Add(new MailboxAddress("Reciever", "*****@*****.**")); _mail.Subject = order.ProductName; try { using var client = new MailKit.Net.Smtp.SmtpClient(); await client.ConnectAsync("smtp.gmail.com", 587, false); await client.AuthenticateAsync(_connectionDataOptions.Value.UserName, _connectionDataOptions.Value.Password); await client.SendAsync(_mail); await client.DisconnectAsync(true); } catch (SmtpException exception) { System.Console.WriteLine(exception.Message); } }
/// <summary> /// Sending emails from application /// </summary> /// <param name="email"></param> /// <param name="subject"></param> /// <param name="message"></param> /// <returns></returns> public async Task SendEmailAsync(string email, string subject, string message) { var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress("PDM Fiorano", "*****@*****.**")); emailMessage.To.Add(new MailboxAddress(email)); emailMessage.Subject = subject; emailMessage.Body = new TextPart("plain") { Text = message }; var client = new MailKit.Net.Smtp.SmtpClient(); //client.LocalDomain = "fiorano.rs"; await client.ConnectAsync("irelay.calzedonia.com", 25, SecureSocketOptions.None).ConfigureAwait(false); await client.SendAsync(emailMessage).ConfigureAwait(false); await client.DisconnectAsync(true).ConfigureAwait(false); //return Task.CompletedTask; }
public async Task <EmailSenderResult> SendEmailAsync(string email, string subject, string message) { try { var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress(_mailSettings.DisplayName, _mailSettings.Mail)); 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(_mailSettings.Host, _mailSettings.Port, false); await client.AuthenticateAsync(_mailSettings.Mail, _mailSettings.Password); await client.SendAsync(emailMessage); await client.DisconnectAsync(true); } return(new EmailSenderResult { IsSuccessful = true, Message = "Ok", }); } catch (Exception exception) { return(new EmailSenderResult { IsSuccessful = false, Message = exception.Message, }); } }
public async Task SendMail(string desMail, string subjectMail, string bodyMail) { //===================== With Mailkit =================== var email = new MimeMessage(); email.Sender = new MailboxAddress(_mailSettings.DisplayName, _mailSettings.Mail); email.From.Add(new MailboxAddress(_mailSettings.DisplayName, _mailSettings.Mail)); email.To.Add(MailboxAddress.Parse(desMail)); email.Subject = subjectMail; email.Body = new TextPart(TextFormat.Plain) { Text = bodyMail }; // using var smtp = new MailKit.Net.Smtp.SmtpClient(); try { smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls); smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password); await smtp.SendAsync(email); } catch (Exception ex) { Console.WriteLine(ex); } smtp.Disconnect(true); //===================== With SMTP Client and serverSMTP Gmail =================== // var email = new MailMessage (from: _mailSettings.DisplayName, to: desMail, subject: subjectMail, body: bodyMail); // email.BodyEncoding = System.Text.Encoding.UTF8; // email.SubjectEncoding = System.Text.Encoding.UTF8; // email.IsBodyHtml = true; // email.ReplyToList.Add (new MailAddress (_mailSettings.DisplayName)); // email.Sender = new MailAddress (_mailSettings.DisplayName); // Tạo SmtpClient kết nối đến smtp.gmail.com // using (SmtpClient client = new SmtpClient ("smtp.gmail.com")) { // client.Port = 587; // client.Credentials = new NetworkCredential (_mailSettings.DisplayName, _mailSettings.Password); // client.EnableSsl = true; // return await SendMail (_mailSettings.DisplayName, desMail, subjectMail, bodyMail, client); // } }
public async void SendMailAsync(string to, string from, string subject, string text) { var message = new MimeKit.MimeMessage(); // 宛先情報 message.From.Add(new MimeKit.MailboxAddress("<宛名>", from)); // 送り元情報 message.To.Add(new MimeKit.MailboxAddress("<送信者名>", to)); // 表題 message.Subject = subject; // 内容 var textPart = new MimeKit.TextPart(MimeKit.Text.TextFormat.Plain); textPart.Text = text; message.Body = textPart; using (var client = new MailKit.Net.Smtp.SmtpClient()) { try { // SMTPサーバに接続 await client.ConnectAsync(SmtpHost, SmtpPort); Debug.WriteLine("接続完了"); // SMTPサーバ認証(あれば) await client.AuthenticateAsync(User, Pass); // 送信 await client.SendAsync(message); // 切断 await client.DisconnectAsync(true); } catch (Exception e) { Debug.WriteLine("{0} Exception caught.", e); } } }
public async Task SendEmailAsync(string subject, string HtmlContent, string Content, List <EmailAddresses> ToAddress, EmailAddresses FromAddress, List <EmailAttachments> Attachments, EmailConfiguration Config) { var message = new MimeMessage { Subject = subject }; message.From.Add(new MailboxAddress(FromAddress.EmailOwner, FromAddress.EmmailAddress)); foreach (var item in ToAddress) { message.To.Add(new MailboxAddress(item.EmailOwner, item.EmmailAddress)); } var bodyBuilder = new BodyBuilder { HtmlBody = Content, TextBody = Regex.Replace(Content, "<[^>]*>", "") }; foreach (var item in Attachments) { bodyBuilder.Attachments.Add(item.AttachmentName, item.Attachment); } message.Body = bodyBuilder.ToMessageBody(); using (var smtp = new MailKit.Net.Smtp.SmtpClient()) { await smtp.ConnectAsync(Config.Server, Config.Port, Config.SecurityOption); await smtp.AuthenticateAsync(Config.UserName, Config.Password); //Send await smtp.SendAsync(message); await smtp.DisconnectAsync(true); } }
public async Task <int> SendEmailConfirmationAsync(string email, string callbackUrl) { var mimeMessage = new MimeMessage(); mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress)); mimeMessage.To.Add(new MailboxAddress(email)); mimeMessage.Subject = "Confirm new account"; var bodyBuilder = new MimeKit.BodyBuilder { HtmlBody = $"<p>If this email comes to your junk folder, copy and paste the link into your browser's address bar, OR click the 'Not Junk' link to move this email to your inbox. At which point, the link will become clickable and it will tell your email client that further emails from Systems Design is safe to put into the inbox.</p><br /><br /> {callbackUrl}" }; mimeMessage.Body = bodyBuilder.ToMessageBody(); using (var client = new MailKit.Net.Smtp.SmtpClient()) { try { client.Connect(_smtpServer, _smtpPort, _enableSsl); client.Authenticate(_username, _password); await client.SendAsync(mimeMessage); _logger.LogInformation("A confirmation email was sent to {0}. Message sent: {1}", email, mimeMessage.Body); } catch (SmtpException ex) { _logger.LogError("An error occurred sending a confimation email: {0}, Message:{1}", ex, ex.Message); throw; } finally { client.Disconnect(true); } } return(await Task.FromResult(0)); }
public async Task SendEmailAsync(string email, string subject, string htmlMessage) { var message = new MimeMessage(); message.To.Add(new MailboxAddress(email)); message.From.Add(new MailboxAddress("BolShoping", "*****@*****.**")); message.Subject = subject; message.Body = new TextPart("html") { Text = htmlMessage }; using (var smtp = new SmtpClient()) { smtp.Connect(_host, _port, _ssl); smtp.Authenticate(_username, _password); await smtp.SendAsync(message); smtp.Disconnect(true); } }
public async void Send(string toAddress, string subject, string body, bool sendAsync = true) { var mimeMessage = new MimeMessage(); // MIME : Multipurpose Internet Mail Extension mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress)); mimeMessage.To.Add(new MailboxAddress(toAddress)); mimeMessage.Subject = subject; var bodyBuilder = new MimeKit.BodyBuilder { HtmlBody = body }; mimeMessage.Body = bodyBuilder.ToMessageBody(); using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect(_smtpServer, _smtpPort, _enableSsl); client.Authenticate(_username, _password); // If using GMail this requires turning on LessSecureApps : https://myaccount.google.com/lesssecureapps if (sendAsync) { await client.SendAsync(mimeMessage); } client.Disconnect(true); } }
public async Task <int> SendEmailAsync(string email, string subject, string message) { // MIME : Multipurpose Internet Mail Extension var mimeMessage = new MimeMessage(); mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress)); mimeMessage.To.Add(new MailboxAddress(email)); mimeMessage.Subject = subject; var bodyBuilder = new MimeKit.BodyBuilder { HtmlBody = message }; mimeMessage.Body = bodyBuilder.ToMessageBody(); using (var client = new MailKit.Net.Smtp.SmtpClient()) { try { client.Connect(_smtpServer, _smtpPort, _enableSsl); //If using GMail this requires turning on LessSecureApps : https://myaccount.google.com/lesssecureapps client.Authenticate(_username, _password); await client.SendAsync(mimeMessage); _logger.LogInformation("A email was sent to {0}. Message sent: {1}", email, mimeMessage.Body); } catch (SmtpException ex) { _logger.LogError("An error occurred sending a confimation email: {0}, Message:{1}", ex, ex.Message); throw; } finally { client.Disconnect(true); } } return(await Task.FromResult(0)); }
public static async Task SendEmailAsync(string email, string subject, string message) { var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress("Администрация бота", "*****@*****.**")); emailMessage.To.Add(new MailboxAddress(email)); emailMessage.Subject = subject; emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Plain) { Text = message }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { await client.ConnectAsync("wpl19.hosting.reg.ru", 587, false); await client.AuthenticateAsync("*****@*****.**", "Diffind123!"); await client.SendAsync(emailMessage); await client.DisconnectAsync(true); } }
static async Task RunClientAsync(string name, int limit = Int32.MaxValue, CancellationToken cancellationToken = default(CancellationToken)) { var counter = 1; while (limit-- > 0 && cancellationToken.IsCancellationRequested == false) { using (var smtpClient = new SmtpClient()) { try { await smtpClient.ConnectAsync("localhost", 9025, false, cancellationToken); await smtpClient.AuthenticateAsync("user", "password", cancellationToken); var message = new MimeKit.MimeMessage(); message.From.Add(new MimeKit.MailboxAddress($"{name}{counter}@test.com")); message.To.Add(new MimeKit.MailboxAddress("*****@*****.**")); message.Subject = $"{name} {counter}"; message.Body = new TextPart(TextFormat.Plain) { //Text = ".Ad", Text = ".Assunto teste acento çãõáéíóú", //Text = "Assunto teste acento", }; await smtpClient.SendAsync(message, cancellationToken).ConfigureAwait(false); } catch (Exception exception) { Console.WriteLine(exception); } await smtpClient.DisconnectAsync(true, cancellationToken); } counter++; } }
public async Task Send(string toAddress, string subject, string body, bool sendAsync = true) { MimeMessage mimeMessage = new MimeMessage(); // MIME : Multipurpose Internet Mail Extension mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress)); mimeMessage.To.Add(new MailboxAddress(string.Empty, toAddress)); mimeMessage.Subject = subject; BodyBuilder bodyBuilder = new MimeKit.BodyBuilder { HtmlBody = body }; mimeMessage.Body = bodyBuilder.ToMessageBody(); using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient()) { await client.ConnectAsync(_smtpServer, _smtpPort, _enableSsl).ConfigureAwait(false); await client.AuthenticateAsync(_username.Trim(), _password.Trim()).ConfigureAwait(false); if (sendAsync) { await client.SendAsync(mimeMessage).ConfigureAwait(false); } else { client.Send(mimeMessage); } client.Disconnect(true); } }
public async Task SenEmailAsync(string email, string subject, string body) { try { var message = new MimeMessage(); message.From.Add(new MailboxAddress(_smtpSettings.SenderName, _smtpSettings.SenderEmail)); message.To.Add(new MailboxAddress(email)); message.Subject = subject; message.Body = new TextPart("html") { Text = body }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.ServerCertificateValidationCallback = (s, c, h, e) => true; if (_env.IsDevelopment()) { await client.ConnectAsync(_smtpSettings.Server, _smtpSettings.Port, true); } else { await client.ConnectAsync(_smtpSettings.Server); } await client.AuthenticateAsync(_smtpSettings.Username, _smtpSettings.Password); await client.SendAsync(message); await client.DisconnectAsync(true); } } catch (Exception ex) { throw new InvalidOperationException(ex.Message); } }
public async Task SendEmailAsync(string mail, string subject, string htmlMessage) { MimeMessage email = new MimeMessage(); // Email from email.From.Add(new MailboxAddress(_config.DisplayName, _config.Mail)); // Mail to email.To.Add(new MailboxAddress(mail, mail)); //Subject email.Subject = subject; //Body var bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = htmlMessage; 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) { System.IO.Directory.CreateDirectory("mailssave"); var emailsavefile = string.Format(@"mailssave/{0}.eml", Guid.NewGuid()); await email.WriteToAsync(emailsavefile); _logger.LogInformation("Lỗi gửi mail, lưu tại - " + emailsavefile); _logger.LogError(ex.Message); } }
public async Task SendAsync(MailModelBL mailModel) { try { MimeMessage message = new MimeMessage(); message.From.Add(new MailboxAddress(_smtpServer.senderName, (string.IsNullOrWhiteSpace(mailModel.From)) ? _smtpServer.senderMail : mailModel.From)); message.To.Add(new MailboxAddress(mailModel.To)); message.Subject = mailModel.Subject; var builder = new BodyBuilder() { HtmlBody = $"<div style=\"color: green;\">{mailModel.Body}</div>" }; if (mailModel.Attachments != null && mailModel.Attachments.Count > 0) { foreach (var attachment in mailModel.Attachments) { builder.Attachments.Add(attachment.FileName, attachment.FileContent); } } message.Body = builder.ToMessageBody(); using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient()) { await client.ConnectAsync(_smtpServer.serverAddress, _smtpServer.serverPort, true); await client.AuthenticateAsync(_smtpServer.userName, _smtpServer.password); await client.SendAsync(message); await client.DisconnectAsync(true); } } catch (Exception e) { throw new InvalidOperationException(e.Message); } }
public async Task <bool> SendEmail(string to, string subject, string message) { var email = new MimeMessage(); email.Sender = new MailboxAddress(mailSettings.DisplayName, mailSettings.Mail); email.From.Add(new MailboxAddress(mailSettings.DisplayName, mailSettings.Mail)); email.To.Add(MailboxAddress.Parse(to)); email.Subject = subject; var builder = new BodyBuilder(); builder.HtmlBody = message; email.Body = builder.ToMessageBody(); using var smtp = new MailKit.Net.Smtp.SmtpClient(); try { smtp.Connect(mailSettings.Host, mailSettings.Port, SecureSocketOptions.StartTls); smtp.Authenticate(mailSettings.Mail, mailSettings.Password); await smtp.SendAsync(email); } catch (Exception ex) { System.IO.Directory.CreateDirectory("mailssave"); var emailsavefile = string.Format(@"mailssave/{0}.eml", Guid.NewGuid()); await email.WriteToAsync(emailsavefile); logger.LogInformation("Lỗi gửi mail, lưu tại - " + emailsavefile); logger.LogError(ex.Message); return(false); } smtp.Disconnect(true); logger.LogInformation("Gửi mail đến " + to); return(true); }
/// <summary> /// /// </summary> /// <param name="ToEmail"></param> /// <param name="Content"></param> /// <param name="Subject"></param> /// <returns></returns> public async Task <bool> SendAsync(string ToEmail, string Content, string Subject) { try { var message = new MimeMessage(); message.From.Add(new MailboxAddress(Encoding.UTF8.GetString(Encoding.Default.GetBytes(emailConfig.FromName)), emailConfig.Account)); message.To.Add(new MailboxAddress(ToEmail, ToEmail)); message.Subject = Subject; var multipart = new Multipart("mixed") { new Multipart("alternative") { new TextPart("plain") { Text = Content } } }; message.Body = multipart; using var client = new MailKit.Net.Smtp.SmtpClient(); await client.ConnectAsync(emailConfig.StmpHost, emailConfig.StmpPort, true); client.AuthenticationMechanisms.Remove("XOAUTH2"); await client.AuthenticateAsync(emailConfig.Account, emailConfig.Auth); await client.SendAsync(message); await client.DisconnectAsync(true); return(true); } catch (Exception ex) { _logger.LogDebug(ex.Message); _logger.LogDebug(ex.StackTrace); return(false); } }
public static async Task <bool> SendMail(string title, string content, MailEntity mailInfo = null) { if (mailInfo == null) { mailInfo = await FileConfig.GetMailInfoAsync(); if (mailInfo.MailPwd.IsNullOrWhiteSpace() || mailInfo.MailFrom.IsNullOrWhiteSpace() || mailInfo.MailHost.IsNullOrWhiteSpace()) { throw new Exception("请先在 [/seting] 页面配置邮箱设置。"); } } var message = new MimeMessage(); message.From.Add(new MailboxAddress(mailInfo.MailFrom, mailInfo.MailFrom)); foreach (var mailTo in mailInfo.MailTo.Replace(";", ";").Replace(",", ";").Replace(",", ";").Split(';')) { message.To.Add(new MailboxAddress(mailTo, mailTo)); } message.Subject = string.Format(title); message.Body = new TextPart("html") { Text = content }; using (var client = new MailKit.Net.Smtp.SmtpClient()) { await client.ConnectAsync(mailInfo.MailHost, 465, true); await client.AuthenticateAsync(mailInfo.MailFrom, mailInfo.MailPwd); await client.SendAsync(message); await client.DisconnectAsync(true); } return(true); }