C#邮件发送工具类

目录结构:

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
    {
        /// 
        /// 判断是否正确的邮箱格式
        /// 
        /// 邮箱地址
        /// bool
        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})(\]?)$");
        }

        /// 
        /// 发送邮件,可发送多个邮箱地址。返回string[发送完成 或 错误信息]
        /// 
        /// 邮件实体
        /// 返回string[发送完成 或 错误信息]
        public static bool SendEmail(Model model, out string info)
        {
            ///Dictionary 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);
        /// 
        /// 定时发送邮件
        /// 
        /// 邮件实体
        /// 预计发送时间
        /// 
        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(), Result);
        }

        #endregion

        /// 
        /// 发送邮件,同时发送多个邮箱。返回string[发送完成 或 错误信息] 注:如果发送失败,会再自动发送,如果连续发送失败3次将会终止发送
        /// 
        /// 收信人地址ArrayList数组
        /// 邮件标题
        /// 邮件内容
        /// 内容格式:false为Text,true为Html
        /// 优先级:0为低,1为中,2为高
        /// string
        private static bool SendEmail(Dictionary toEmail, string subject, string body, bool bodyHTML, int priority, List 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 item in toEmail)
            {
                if (!IsEmail(item.Key))
                {
                    errEmail += item.Key + "
"; } 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 += "
以下邮箱地址格式有问题:
" + 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
{
    /// 
    /// 发送邮件异常
    /// 
    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
{
    /// 
    /// 邮箱实体
    /// 
    [Serializable]
    public class Model : ICloneable
    {
        private Dictionary toEmail = new Dictionary();
        private string subject;
        private string body;
        private ContentFormat format = ContentFormat.TEXT;
        private Priority priority = Priority.Normal;
        private List attachmentPhysicalPath = new List();

        /// 
        /// 收件人的邮箱地址集合
        /// 
        public Dictionary ToEmail
        {
            get { return toEmail; }
            set { toEmail = value; }
        }

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

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

        /// 
        /// 字符串转换成邮箱 重复的邮箱会自动去掉 第一个为发送(MailType.send) 其它为抄送(MailType.copy)
        /// 
        /// 
        /// 
        /// 分割符号
        /// 
        public static bool stringToEmail(string str, out Dictionary toEmail, out string info, char splitSymbol = '|', StrToEmailType Type = StrToEmailType.第一个为发送_其他为抄送)
        {
            toEmail = new Dictionary();
            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;
        }

        /// 
        /// 移除所有的类型为发送的邮箱
        /// 
        /// 
        public static void RemoveSend(Dictionary toEmail) 
        {
            if (toEmail == null) return;
            ArrayList temp = new ArrayList();
            foreach (KeyValuePair 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);
            }
        }

        /// 
        /// 深复制邮箱
        /// 
        /// 
        /// 全部为抄送、根据实际MailType
        public void ToEmailJoin(Dictionary Emailes, bool IsCopy = true) 
        {
            foreach (KeyValuePair 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);
        }
    }
}






你可能感兴趣的:(C#,C#工具类)