using Furion.Logging; using MailKit.Net.Smtp; using MailKit.Security; using MimeKit; using Myshipping.Core.Entity; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Myshipping.Core.Helper { public static class MailSendHelper { /// /// 使用用户邮箱配置发送邮件 /// /// /// /// /// public static async Task> SendMail(DjyUserMailAccount acc, string subject, string body, string sendTo) { SmtpClient client = null; try { var message = new MimeMessage(); if (!string.IsNullOrEmpty(acc.ShowName)) { message.From.Add(new MailboxAddress(acc.ShowName, acc.MailAccount)); } else { message.From.Add(MailboxAddress.Parse(acc.MailAccount)); } //分隔符不统一,统一替换成分号 sendTo = sendTo.Replace(",", ";"); if (sendTo.IndexOf(";") > -1) { var arrSendTo = sendTo.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (var s in arrSendTo) { var trimStr = s.Trim(); if (!string.IsNullOrEmpty(trimStr)) { message.To.Add(MailboxAddress.Parse(trimStr)); } } } else { message.To.Add(MailboxAddress.Parse(sendTo)); } message.Subject = subject; var html = new TextPart("html") { Text = body }; MimeEntity entity = html; message.Sender = MailboxAddress.Parse(acc.MailAccount); message.Body = entity; using (client = new SmtpClient()) { Log.Information($"准备发送邮件{subject} 从【{acc.MailAccount}】到【{sendTo}】,{acc.SmtpServer} {acc.SmtpPort} {acc.SmtpSSL}"); await client.ConnectAsync(acc.SmtpServer, acc.SmtpPort.Value, acc.SmtpSSL.HasValue && acc.SmtpSSL.Value ? SecureSocketOptions.SslOnConnect : SecureSocketOptions.None); await client.AuthenticateAsync(acc.MailAccount, acc.Password); await client.SendAsync(message); await client.DisconnectAsync(true); } Log.Information($"mail send success:{subject}"); return new KeyValuePair(true, "发送成功"); } catch (Exception ex) { Log.Error($"mail send fail:{subject} 从【{acc.MailAccount}】到【{sendTo}】,{acc.SmtpServer} {acc.SmtpPort} {acc.SmtpSSL}"); Log.Error(ex.Message); Log.Error(ex.StackTrace); return new KeyValuePair(false, ex.Message); } } } }