/*--------------------------------------------------------------------- * Copyright (C) 2024 TECHSCAN 版权所有。 * www.techscan.cn *┌──────────────────────────────────┐ *│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │ *│ 版权所有:上海太迅自动识别技术有限公司               │ *└──────────────────────────────────┘ * * 文件名: MailKitHelp.cs * 功能描述: N/A * 作者: 26950 * CLR版本: 4.0.30319.42000 * 创建时间: 2024/3/14 12:24:08 * Client: MAYONGLONG * 文件版本: V1.0.0 ===============================版本履历=============================== * Ver 变更日期 负责人 变更内容 * V1.0.0 2024/3/14 12:24:08 Myl Create * ====================================================================== //--------------------------------------------------------------------*/ using MailKit.Net.Smtp; using MailKit.Security; using MimeKit; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace TsSFCDeivceClient.Email { public class MailKitHelp { /// /// 邮件发送状态 /// public enum SendStatus { /// /// 默认,正常,准备发送 /// Normal = 0, /// /// 发送成功 /// Success = 1, /// /// 发送失败 /// Failed = 2, /// /// 发送邮箱或收件邮箱未通过验证 /// Unmatch = 3, /// /// 发件地址未通过验证 /// SendMailAddressIsUnmatch = 4, /// /// 发件密码为空 /// PassWordIsNull = 5, /// /// 收件地址未通过验证 /// FromMailAddressIsUnmatch = 6 } /// /// 发送标题和内容的字符集,默认是UTF8 /// public Encoding CharSet = Encoding.UTF8; /// /// 设置指示邮件正文是否为 Html 格式 /// 默认为False,不是Html格式 /// public bool IsBodyHtml = false; /// /// 是否使用抄送 /// public bool IsCC = false; /// /// 是否发送附件 /// public bool IsSendAttachments = false; /// /// 是否开启安全套接字层 (SSL) 加密连接 /// public bool IsSSL = false; /// /// SMTP服务器是否不需要身份认证 /// 默认为False,需要使用账号和密码登陆 /// public bool IsUseDefaultCredentials = false; /// /// 邮箱正则表达式(不区分大小写),可修改成自定义正则表达式 /// public string RegexText = @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; /// /// Smtp 服务器端口,默认25 /// public int SmtpPort = 25; /// /// 邮件附件 /// 如果确定发送附件请将IsSendAttachments设置为true /// public List Attachments { get; set; } /// /// 邮件正文内容 /// public string Body { get; set; } /// /// 邮件的抄送者 /// 如果确定发送邮件的抄送者请将IsCC设置为true /// public string[] CarbonCopy { get; set; } /// /// 收件邮箱地址 /// public string[] ToMailAddress { get; set; } /// /// 邮箱密码 /// public string PassWord { get; set; } /// /// 发件邮箱地址 /// public string FromMailAddress { get; set; } /// /// 发件邮箱昵称 ,默认为发件地址 /// public string SendMailNickName { get; set; } /// /// Smtp 服务器地址 /// public string SmtpAddress { get; set; } /// /// 邮件标题 /// public string Title { get; set; } /// /// 发送邮件,并且返回发送结果 /// /// public SendStatus Send(out string relustMessage) { relustMessage = string.Empty; #region 验证基本信息 Regex reg = new Regex(this.RegexText, RegexOptions.IgnoreCase); if (!IsUseDefaultCredentials) // 使用账号密码登陆Smtp服务 { if (!reg.IsMatch(this.FromMailAddress)) { relustMessage = "发件地址未通过验证"; return SendStatus.SendMailAddressIsUnmatch; } if (string.IsNullOrEmpty(this.PassWord)) { relustMessage = "发件密码为空"; return SendStatus.PassWordIsNull; } } if (this.ToMailAddress == null || this.ToMailAddress.Length <= 0) { relustMessage = "收件地址为空"; return SendStatus.FromMailAddressIsUnmatch; } StringBuilder FailedELst = new StringBuilder(); foreach (string item in this.ToMailAddress) { if (!reg.IsMatch(item)) { FailedELst.Append(Environment.NewLine + item); } } if (FailedELst.Length > 0) { relustMessage = "以下收件地址未通过验证:" + FailedELst; return SendStatus.FromMailAddressIsUnmatch; } #endregion 验证基本信息 MimeMessage msg = new MimeMessage(); msg.From.Add(new MailboxAddress(this.FromMailAddress, this.FromMailAddress)); foreach (string t in ToMailAddress) { msg.To.Add(new MailboxAddress(t, t)); } //抄送 if (this.CarbonCopy != null && this.CarbonCopy.Length > 0 && this.IsCC) // 是否显示抄送 { foreach (string item in this.CarbonCopy) { msg.Cc.Add(new MailboxAddress(item, item)); } } msg.Subject = this.Title; //邮件标题 var bodyBuilder = new BodyBuilder(); if (IsBodyHtml) { bodyBuilder.HtmlBody = this.Body; } else { bodyBuilder.TextBody = this.Body; } Multipart multipart = new Multipart("mixed") { bodyBuilder.ToMessageBody() }; // 添加附件 if (this.Attachments != null && this.Attachments.Count > 0 && this.IsSendAttachments) { foreach (MimePart item in this.Attachments) { multipart.Add(item); } } msg.Body = multipart; string vSendMsg = ""; SendStatus sendStatus = SendStatus.Normal; try { using (var client = new SmtpClient()) { client.CheckCertificateRevocation = false; client.ServerCertificateValidationCallback = (s, c, h, e) => true; //smtp服务器,端口,是否开启ssl client.Connect(SmtpAddress, SmtpPort, (IsSSL ? SecureSocketOptions.Auto : SecureSocketOptions.None)); if (!IsUseDefaultCredentials) client.Authenticate(FromMailAddress, PassWord); client.Send(msg); client.Disconnect(true); } relustMessage = $"邮件发送成功!{vSendMsg}"; sendStatus = SendStatus.Success; } catch (Exception ee) { sendStatus = SendStatus.Failed; relustMessage = ee.InnerException == null ? ee.Message : ee.InnerException.ToString(); } return sendStatus; } public string GetHtmlInfoString(string cMsg) { string lsMailFormatPath = string.Empty; lsMailFormatPath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Email"), "MailSuccess.html"); //string.Format("{0}{1}", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Email"), "MailSuccess.html"); string basicMailContent = ""; using (StreamReader objReader = new StreamReader(lsMailFormatPath, Encoding.UTF8)) { basicMailContent = objReader.ReadToEnd(); } basicMailContent = basicMailContent.Replace("#SFC{{0}}SFC#", cMsg); return basicMailContent; } } }