分享一个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();
    }

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;
        }
    }

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

使用方法:

//同步发送
EmailWrapper.Initalize
    .SetHost("smtp.xxxxx.com")
    .SetPort(25)
    .SetUserName("[email protected]")
    .SetPassword("******")
    .SetSSL(false)
    .SetFromAddress("[email protected]")
    .SetFromDisplayName("Felix")
    .SetToAddress("[email protected]", "[email protected]")
    .SetCcAddress("[email protected]")
    .SetSubject("会员注册成功")
    .SetBody("恭喜你成为会员,为了你的账号安全,请尽快前往安全中心修改登录密码。")
    .Send();

//异步发送 从CONFIG中加载配置
await EmailWrapper.Initalize
    .LoadFromConfigFile()
    .SetFromDisplayName("Felix")
    .SetToAddress("[email protected]")
    .SetToAddress("[email protected]")
    .SetToAddress("[email protected]")
    .SetSubject("会员注册成功")
    .SetBody("恭喜你成为会员,为了你的账号安全,请尽快前往安全中心修改登录密码。")
    .SendAsync();
时间: 2024-10-10 20:59:25

分享一个Fluent风格的邮件发送封装类的相关文章

asp.net core 2.0 邮件发送服务

网上找了一下,发现一个很不错的邮件发送服务Mailgun,首先要注册Mailgun账号,获得apikey以及domainame: 然后项目中安装nuget: 配置并注册服务: public interface IEmailSender { Task SendEmailAsync(string email, string subject, string message); } public class EmailSender:IEmailSender { private readonly Emai

c# 邮件发送代码分享

/// <summary> /// 发送邮件方法 /// </summary> /// <param name="sendMail">发送人</param> /// <param name="recMail">接收人(可以是多个,用;分号隔开)</param> /// <param name="subject">主题</param> /// <p

xampp 和thinkphp 建一个本地站并实现邮件发送功能

一.xampp的安装使用 1.首先看下什么是xampp,想要建站的小伙伴肯定都知道,XAMPP(Apache+MySQL+PHP+PERL)是一个功能强大的建 XAMPP 软件站集成软件包. 它可以在Windows.Linux.Solaris.Mac OS X 等多种操作系统下安装使用 2.需要什么版本到官网上下载:xampp下载 3.安装很简单,傻瓜式安装,感觉mysql选项可以去掉,自己安装一个,具体安装看这个:mysql安装,另外路径建议只改动盘符,保留后缀路径 4.安装好的目录如下 5.

一个简短非常实用的邮件发送

import java.util.Properties;import javax.mail.Authenticator;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.Addre

使用Spring的JAVA Mail支持简化邮件发送(转)

闲来无事,翻看<Spring in Action>,发现Spring集成了对JAVA Mail的支持,有点小激动的看了一遍,嗯,话说真的简单了很多. Spring的邮件发送的核心是MailSender接口,在Spring3.0中提供了一个实现类JavaMailSenderImpl,这个类是发送邮件的核心类.可以通过在配置文件中配置使用,当然也可以自己硬编码到代码中(方便起见,下面的演示代码都是硬编码到代码中,省得配置麻烦). Spring提供的邮件发送不仅支持简单邮件的发送.添加附件,而且还可

使用phantomjs实现highcharts等报表通过邮件发送

使用phantomjs实现highcharts等报表通过邮件发送(本文仅提供完整解决方案和实现思路,完全照搬不去整理代码无法马上得到效果) 前不久项目组需要将测试相关的质量数据通过每日自动生成报表展示,并自动通过将报表作为邮件正文内容知会到干系人邮箱.那么问题来了,报表生成了,但是邮件怎么发送,因为highcharts等报表都是通过JS和HTML在前端浏览器进行渲染生成的,而最要命的是邮箱为了安全起见一般都不支持JS,所以就算后台计算出了报表所需的数据,但是也无法在邮件内容中生成报表. 后来想到

分享一个Unity3D小作品,欢迎索取源码!

在一年多前知道了Unity这款游戏引擎.在得知她极大地简化游戏开发的难度并可以使用我最熟悉的C#开发后,便毅然决然地开始学习Unity3D.说来惭愧,期间,由于个人原因,学习断断续续,直到现在才有一个勉强拿的出手的小作品.这款小游戏是一款类似超级马里奥的冒险游戏,玩法简单明了不费脑. 游戏截图 菜单界面 查看最高分 设置游戏难度,主要是设置主角受攻击时的伤害 可以通过跳跃攻击小怪兽 匕首攻击 滑行越过障碍物 乘坐来回移动的平台去往目的地 你赢了!就这样! 操作键设置 在该项目中自定义了几个操作键

.NET开发邮件发送功能的全面教程(含邮件组件源码)

ref: http://www.cnblogs.com/heyuquan/p/net-batch-mail-send-async.html 今天,给大家分享的是如何在.NET平台中开发"邮件发送"功能.在网上搜的到的各种资料一般都介绍的比较简单,那今天我想比较细的整理介绍下: 1)         邮件基础理论知识 2)         邮件发送相关.NET类库 3)         介绍我开发的一个发送邮件的小组件(MailHelper) 4)         MailHelper组

Spring Boot 2.0 图文教程 | 集成邮件发送功能

文章首发自个人微信公众号: 小哈学Java 个人网站: https://www.exception.site/springboot/spring-boots-send-mail 大家好,后续会间断地奉上一些 Spring Boot 2.x 相关的博文,包括 Spring Boot 2.x 教程和 Spring Boot 2.x 新特性教程相关,如 WebFlux 等.还有自定义 Starter 组件的进阶教程,比如:如何封装一个自定义图床 Starter 启动器(支持上传到服务器内部,阿里 OS