码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-07-21 00:32:12      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:

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();

 

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

标签:

原文地址:http://www.cnblogs.com/felixnet/p/5690006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!