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 void 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}"); client.Connect(acc.SmtpServer, acc.SmtpPort.Value, acc.SmtpSSL.HasValue && acc.SmtpSSL.Value ? SecureSocketOptions.SslOnConnect : SecureSocketOptions.None); client.Authenticate(acc.MailAccount, acc.Password); client.Send(message); client.Disconnect(true); } Log.Information($"mail send success:{subject}"); } 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); } } } }