• 分享一个Fluent风格的邮件发送封装类


    C#中用SmtpClient发邮件很简单,闲着无事,简单封装一下

    IEmailFactory

    public interface IEmailFactory
        {
            IEmailFactory SetHost(string host);
            IEmailFactory SetPort(int port);
            IEmailFactory SetUserName(string userName);
            IEmailFactory SetPassword(string password);
            IEmailFactory SetSSL(bool enableSsl);
            IEmailFactory SetTimeout(int timeout);
            IEmailFactory SetFromAddress(string address);
            IEmailFactory SetFromDisplayName(string displayName);
            IEmailFactory LoadFromConfigFile(); //从Config文件中加载配置
            IEmailFactory SetSubject(string subject);
            IEmailFactory SetBody(string body);
            /// <summary>
            /// 添加收件人地址(执行多次即添加多个地址)
            /// </summary>
            IEmailFactory SetToAddress(params string[] addresses);
            /// <summary>
            /// 添加抄送人地址(执行多次即添加多个地址)
            /// </summary>
            IEmailFactory SetCcAddress(params string[] addresses);
            /// <summary>
            /// 添加附件(执行多次即添加多个附件)
            /// </summary>
            IEmailFactory SetAttachment(params Attachment[] attachments);
    
            void Send();
            Task SendAsync();
        }
    View Code

    EmailFactory

    class EmailFactory : IEmailFactory
        {
            #region properties
            protected string Host { get; set; }
            protected int Port { get; set; }
            protected string UserName { get; set; }
            protected string Password { get; set; }
            protected bool EnableSSL { get; set; }
            protected int? Timeout { get; set; }
            protected string FromAddress { get; set; }
            protected string FromDisplayName { get; set; }
            protected string Subject { get; set; }
            protected string Body { get; set; }
            protected IList<string> ToList { get; set; }
            protected IList<string> CcList { get; set; }
            protected IList<Attachment> Attachments { get; set; }
            #endregion
    
            #region initial methods
            public IEmailFactory SetHost(string host)
            {
                this.Host = host;
                return this;
            }
            public IEmailFactory SetPort(int port)
            {
                this.Port = port;
                return this;
            }
            public IEmailFactory SetSSL(bool enableSsl)
            {
                this.EnableSSL = enableSsl;
                return this;
            }
            public IEmailFactory SetTimeout(int timeout)
            {
                this.Timeout = timeout;
                return this;
            }
            public IEmailFactory SetUserName(string userName)
            {
                this.UserName = userName;
                return this;
            }
            public IEmailFactory SetPassword(string password)
            {
                this.Password = password;
                return this;
            }
            public IEmailFactory SetFromAddress(string address)
            {
                this.FromAddress = address;
                return this;
            }
            public IEmailFactory SetFromDisplayName(string displayName)
            {
                this.FromDisplayName = displayName;
                return this;
            }
            public IEmailFactory LoadFromConfigFile()
            {
                var section = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as System.Net.Configuration.SmtpSection;
                this.Host = section.Network.Host;
                this.Port = section.Network.Port;
                this.EnableSSL = section.Network.EnableSsl;
                this.UserName = section.Network.UserName;
                this.Password = section.Network.Password;
                this.FromAddress = section.From;
                return this;
            }
            public IEmailFactory SetSubject(string subject)
            {
                this.Subject = subject;
                return this;
            }
            public IEmailFactory SetBody(string body)
            {
                this.Body = body;
                return this;
            }
            public IEmailFactory SetToAddress(params string[] addresses)
            {
                if (this.ToList == null) this.ToList = new List<string>();
                if (addresses != null)
                    foreach (var item in addresses)
                        this.ToList.Add(item);
    
                return this;
            }
            public IEmailFactory SetCcAddress(params string[] addresses)
            {
                if (this.CcList == null) this.CcList = new List<string>();
                if (addresses != null)
                    foreach (var item in addresses)
                        this.CcList.Add(item);
    
                return this;
            }
            public IEmailFactory SetAttachment(params Attachment[] attachments)
            {
                if (this.Attachments == null) this.Attachments = new List<Attachment>();
                if (attachments != null)
                    foreach (var item in attachments)
                        this.Attachments.Add(item);
    
                return this;
            }
            #endregion
           
            public virtual void Send()
            {
                using (SmtpClient smtp = new SmtpClient(this.Host, this.Port))
                {
                    var message = PreSend(smtp);
                    smtp.Send(message);
                }
            }
            public virtual async Task SendAsync()
            {
                using (SmtpClient smtp = new SmtpClient(this.Host, this.Port))
                {
                    var message = PreSend(smtp);
                    await smtp.SendMailAsync(message);
                }
            }
    
            private MailMessage PreSend(SmtpClient smtp)
            {
                if (this.UserName != null && this.Password != null)
                {
                    smtp.UseDefaultCredentials = false;
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtp.Credentials = new System.Net.NetworkCredential(this.UserName, this.Password);
                }
                if (this.Timeout == null)
                    smtp.Timeout = 60000;
    
                var message = new MailMessage();
                message.From = new MailAddress(this.FromAddress, this.FromDisplayName, Encoding.UTF8);
    
                if (this.ToList != null)
                    foreach (var address in this.ToList)
                        message.To.Add(address);
    
                if (this.CcList != null)
                    foreach (var address in this.CcList)
                        message.CC.Add(address);
    
                if (this.Attachments != null)
                    foreach (var attachment in this.Attachments)
                        message.Attachments.Add(attachment);
    
                message.Subject = this.Subject;
                message.SubjectEncoding = Encoding.UTF8;
                message.Body = this.Body;
                message.IsBodyHtml = true;
                message.BodyEncoding = Encoding.UTF8;
                message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                return message;
            }        
        }
    View Code

    EmailWrapper

    public class EmailWrapper
        {
            private static readonly EmailHelper _instance = new EmailHelper();
            private EmailHelper() { }
    
            public static IEmailFactory Initalize
            {
                get { return _instance.GetFactory(); }
            }
            private IEmailFactory GetFactory()
            {
                return new EmailFactory();
            }
        }
    View Code

    使用方法:

    //同步发送
    EmailWrapper.Initalize
        .SetHost("smtp.xxxxx.com")
        .SetPort(25)
        .SetUserName("xxx@xxxxx.com")
        .SetPassword("******")
        .SetSSL(false)
        .SetFromAddress("xxx@xxxxx.com")
        .SetFromDisplayName("Felix")
        .SetToAddress("f5.zhang@qq.com", "f5.lee@gmail.com")
        .SetCcAddress("f5.chow@yahoo.com")
        .SetSubject("会员注册成功")
        .SetBody("恭喜你成为会员,为了你的账号安全,请尽快前往安全中心修改登录密码。")
        .Send();
    
    //异步发送 从CONFIG中加载配置
    await EmailWrapper.Initalize
        .LoadFromConfigFile()
        .SetFromDisplayName("Felix")
        .SetToAddress("f5.zhang@qq.com")
        .SetToAddress("f5.lee@gmail.com")
        .SetToAddress("f5.chow@yahoo.com")
        .SetSubject("会员注册成功")
        .SetBody("恭喜你成为会员,为了你的账号安全,请尽快前往安全中心修改登录密码。")
        .SendAsync();
  • 相关阅读:
    Linux中将两块新硬盘合并成一个,挂载到/data目录下
    linux将硬盘格式化为xfs文件系统
    nginx配置文件
    centos 添加新硬盘,lvm对根目录扩容
    centos7重新调整分区大小
    Linux 一种调用蜂鸣器的方法
    mybatis中 keyProperty="id" 的作用
    MySQL实战45讲
    常用正则表达式最强整理(速查手册)
    linux下nacos的1.1.3版本集群部署
  • 原文地址:https://www.cnblogs.com/felixnet/p/5690006.html
Copyright © 2020-2023  润新知