C#邮件发送工具类

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/A1090144284/article/details/76577068

目录结构:

Commom

EMail

Mail.cs

MailError.cs

Model.cs


Mail.cs //填写相应的  邮箱的服务器地址、发件人姓名、邮箱、密码信息

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Net;
using ThingsService.Commom;
using System.Threading;
using System.Linq;

namespace Common.EMail
{
    class Mail
    {
        /// <summary>
        /// 判断是否正确的邮箱格式
        /// </summary>
        /// <param name="str_Email">邮箱地址</param>
        /// <returns>bool</returns>
        public static bool IsEmail(string str_Email)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(str_Email, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        /// <summary>
        /// 发送邮件,可发送多个邮箱地址。返回string[发送完成 或 错误信息]
        /// </summary>
        /// <param name="model">邮件实体</param>
        /// <returns>返回string[发送完成 或 错误信息]</returns>
        public static bool SendEmail(Model model, out string info)
        {
            ///Dictionary<string, MailType> toEmail, string subject, string body, bool bodyHTML, int priority, string reportFile
            if (model.ToEmail != null && model.ToEmail.Count > 0)
            {
                if (model.Format == ContentFormat.HTML)
                {
                    return SendEmail(model.ToEmail, model.Subject, model.Body, true, (int)model.Priority, model.AttachmentPhysicalPath, out info);
                }
                else
                {
                    return SendEmail(model.ToEmail, model.Subject, model.Body, false, (int)model.Priority, model.AttachmentPhysicalPath, out info);
                }
            }
            else
            {
                info = "邮箱地址不能为空。";
                return false;
            }
        }

        #region --定时发送邮件
        delegate void del_timingSendEmail(Model model, TimeSpan timeout);
        /// <summary>
        /// 定时发送邮件
        /// </summary>
        /// <param name="model">邮件实体</param>
        /// <param name="sendDateTime">预计发送时间</param>
        /// <returns></returns>
        public static bool TimingSendEmail(Model model, DateTime sendDateTime, out string Result)
        {
            if (model.ToEmail.Count > 0)
            {
                if (sendDateTime != null && DateTime.Now < sendDateTime)
                {
                    Model EModel = (Model)model.Clone();
                    var del = new del_timingSendEmail(TimingSendEmailHandel);
                    var timeout = sendDateTime - DateTime.Now;
                    del.BeginInvoke(EModel, timeout, null, null);
                    Result = string.Format("系统将在{0}天{1}小时{2}分{3}秒后发送该邮件!", timeout.Days, timeout.Hours, timeout.Minutes, timeout.Seconds);
                    return true;
                }
                else
                {
                    return SendEmail(model, out Result);
                }
            }
            else
            {
                Result = "邮箱地址至少得有一个";
                return false;
            }
        }

        static void TimingSendEmailHandel(Model model, TimeSpan timeout)
        {
            Thread.Sleep(timeout);
            string Result;
            SendEmail(model, out Result);
            Console.WriteLine("{0} {1}发送结果:{2}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:sss"), model.ToEmail.Keys.First<string>(), Result);
        }

        #endregion

        /// <summary>
        /// 发送邮件,同时发送多个邮箱。返回string[发送完成 或 错误信息] 注:如果发送失败,会再自动发送,如果连续发送失败3次将会终止发送
        /// </summary>
        /// <param name="mailTo">收信人地址ArrayList数组</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="body">邮件内容</param>
        /// <param name="bodyHTML">内容格式:false为Text,true为Html</param>
        /// <param name="priority">优先级:0为低,1为中,2为高</param>
        /// <returns>string</returns>
        private static bool SendEmail(Dictionary<string, MailType> toEmail, string subject, string body, bool bodyHTML, int priority, List<string> reportFile, out string info)
        {
            info = string.Empty;
            if (string.IsNullOrEmpty(subject))
            {
                info = "邮件标题不能为空!";
                return false;
            }
            string errEmail = "";

            string smtp = "";         //发信人所用邮箱的服务器
            string mailPwd = "";      //发件人的密码
            string mailTrueName = ""; //发件人的姓名
            string mailForm = "";     //发件人的邮箱

            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            foreach (KeyValuePair<string, MailType> item in toEmail)
            {
                if (!IsEmail(item.Key))
                {
                    errEmail += item.Key + "<br />";
                }
                else
                {
                    if (item.Value == MailType.send)
                    {
                        msg.To.Add(item.Key);
                    }
                    else if (item.Value == MailType.copy)
                    {
                        if (toEmail.Count > 1)
                        {
                            msg.CC.Add(item.Key);
                        }
                        else
                        {
                            info = "参数toEmail里至少得有一个邮箱地址为MailType.send!";
                            return false;
                        }
                    }
                }
            }
            msg.From = new MailAddress(mailForm, mailTrueName, System.Text.Encoding.UTF8);
            /* 上面3个参数分别是发件人地址(可以随便写),发件人姓名,编码*/
            msg.Subject = subject;
            msg.SubjectEncoding = System.Text.Encoding.UTF8;
            msg.Body = body;
            msg.BodyEncoding = System.Text.Encoding.UTF8;
            msg.IsBodyHtml = bodyHTML;  //是否是HTML邮件
            //邮件优先级
            if (priority == 0)
                msg.Priority = MailPriority.Low;
            else if (priority == 1)
                msg.Priority = MailPriority.Normal;
            else
                msg.Priority = MailPriority.High;
            ///附件为空
            Attachment datAttachment;
            foreach (string item in reportFile)
            {
                datAttachment = new Attachment(item, System.Net.Mime.MediaTypeNames.Application.Octet);
                System.Net.Mime.ContentDisposition disposition = datAttachment.ContentDisposition;
                disposition.CreationDate = System.IO.File.GetCreationTime(item);
                disposition.ModificationDate = System.IO.File.GetLastWriteTime(item);
                disposition.ReadDate = System.IO.File.GetLastAccessTime(item);
                msg.Attachments.Add(datAttachment);
            }

            //创建Smtp Mail对象
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.UseDefaultCredentials = false;   //要在下一行之前,否则无法登录服务器
            smtpClient.Credentials = new NetworkCredential(mailForm, mailPwd);
            smtpClient.Port = 25;
            smtpClient.Host = smtp;
            smtpClient.EnableSsl = false;
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; //指定如何处理待发的邮件

            int number = 3;
        agin:
            try
            {
                smtpClient.Send(msg);
                info = "发送完成!";
                if (errEmail != "")
                    info += "<hr /><strong>以下邮箱地址格式有问题:</strong><br />" + errEmail;
                return true;
            }
            catch (SmtpException ex)
            {
                if (number > 0)
                {
                    number--;
                    Console.WriteLine(":重新发送【{0}】次", number);
                    goto agin;
                }
                else
                {
                    info = ex.ToString() + ex.StackTrace;
                    return false;
                }
            }
        }
    }
}





MailError.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace ThingsService.Common.EMail
{
    /// <summary>
    /// 发送邮件异常
    /// </summary>
    public class MailError : Exception
    {
        private string message;
        public MailError(string message)
        {
            this.message = message;
        }
        public override string Message
        {
            get
            {
                return this.message;
            }
        }
        public override string ToString()
        {
            return this.message;
        }
    }
}



Model.cs

using System;
using System.Collections.Generic;
using System.Text;
using Commom;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace Common.EMail
{
    /// <summary>
    /// 邮箱实体
    /// </summary>
    [Serializable]
    public class Model : ICloneable
    {
        private Dictionary<string, MailType> toEmail = new Dictionary<string, MailType>();
        private string subject;
        private string body;
        private ContentFormat format = ContentFormat.TEXT;
        private Priority priority = Priority.Normal;
        private List<string> attachmentPhysicalPath = new List<string>();

        /// <summary>
        /// 收件人的邮箱地址集合
        /// </summary>
        public Dictionary<string, MailType> ToEmail
        {
            get { return toEmail; }
            set { toEmail = value; }
        }

        /// <summary>
        /// 邮件主题
        /// </summary>
        public string Subject
        {
            get { return subject; }
            set { subject = value; }
        }
        /// <summary>
        /// 邮件内容
        /// </summary>
        public string Body
        {
            get {
                if (string.IsNullOrEmpty(body))
                    body = "";//设置默认值
                return body;
            }
            set { body = value; }
        }
        /// <summary>
        /// 内容格式 默认为Text
        /// </summary>
        public ContentFormat Format
        {
            get { return format; }
            set { format = value; }
        }
        /// <summary>
        /// 邮件发送级别 默认为中
        /// </summary>
        public Priority Priority
        {
            get { return priority; }
            set { priority = value; }
        }
        /// <summary>
        /// 附件的物理路径
        /// </summary>
        public List<string> AttachmentPhysicalPath
        {
            get { return attachmentPhysicalPath; }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public void ReSet()
        {
            toEmail.Clear();
            subject = string.Empty;
            body = string.Empty;
            format = ContentFormat.TEXT;
            priority = Priority.Normal;
            attachmentPhysicalPath.Clear();
        }

        /// <summary>
        /// 字符串转换成邮箱 重复的邮箱会自动去掉 第一个为发送(MailType.send) 其它为抄送(MailType.copy)
        /// </summary>
        /// <param name="str"></param>
        /// <param name="info"></param>
        /// <param name="splitSymbol">分割符号</param>
        /// <returns></returns>
        public static bool stringToEmail(string str, out Dictionary<string, MailType> toEmail, out string info, char splitSymbol = '|', StrToEmailType Type = StrToEmailType.第一个为发送_其他为抄送)
        {
            toEmail = new Dictionary<string, MailType>();
            info = string.Empty;
            bool result;
            string[] EArry = str.Split('|');

            if (EArry.Length > 0)
            {
                MailType tmp;
                for (sbyte i = 0; i < EArry.Length; i++)
                {
                    if (!EMail.Mail.IsEmail(EArry[i])) { continue; }
                    if (toEmail.TryGetValue(EArry[i], out tmp)) { continue; }
                    if (i == 0)
                    {
                        if (Type == StrToEmailType.第一个为发送_其他为抄送)
                        {
                            toEmail.Add(EArry[i], MailType.send);
                        }
                        else 
                        {
                            toEmail.Add(EArry[i], MailType.copy);
                        }
                    }
                    else
                    {
                        toEmail.Add(EArry[i], MailType.copy);
                    }
                }
                if (toEmail.Count > 0)
                {
                    result = true;
                }
                else 
                {
                    info = "邮箱格式错误!";
                    result = false;
                }
            }
            else 
            {
                info = "邮箱为空!";
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 移除所有的类型为发送的邮箱
        /// </summary>
        /// <param name="toEmail"></param>
        public static void RemoveSend(Dictionary<string, MailType> toEmail) 
        {
            if (toEmail == null) return;
            ArrayList temp = new ArrayList();
            foreach (KeyValuePair<string, MailType> Item in toEmail) 
            {
                if (Item.Value == MailType.send) 
                {
                    if (Item.Key == null) continue;
                    temp.Add(Item.Key);
                }
            }
            foreach (string item in temp) 
            {
                toEmail.Remove(item);
            }
        }

        /// <summary>
        /// 深复制邮箱
        /// </summary>
        /// <param name="Emailes"></param>
        /// <param name="IsCopy">全部为抄送、根据实际MailType</param>
        public void ToEmailJoin(Dictionary<string, MailType> Emailes, bool IsCopy = true) 
        {
            foreach (KeyValuePair<string, MailType> Item in Emailes)
            {
                if (this.ToEmail.ContainsKey(Item.Key)) continue;

                if (IsCopy)
                    this.ToEmail.Add(Item.Key, MailType.copy);
                else
                    this.ToEmail.Add(Item.Key, Item.Value);
            }
        }

        public object Clone()
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            bf.Serialize(ms, this);
            ms.Seek(0, SeekOrigin.Begin);
            return bf.Deserialize(ms);
        }
    }
}






展开阅读全文

没有更多推荐了,返回首页