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

IEmailFactory

  1. public interface IEmailFactory
  2. {
  3. IEmailFactory SetHost(string host);
  4. IEmailFactory SetPort(int port);
  5. IEmailFactory SetUserName(string userName);
  6. IEmailFactory SetPassword(string password);
  7. IEmailFactory SetSSL(bool enableSsl);
  8. IEmailFactory SetTimeout(int timeout);
  9. IEmailFactory SetFromAddress(string address);
  10. IEmailFactory SetFromDisplayName(string displayName);
  11. IEmailFactory LoadFromConfigFile(); //从Config文件中加载配置
  12. IEmailFactory SetSubject(string subject);
  13. IEmailFactory SetBody(string body);
  14. /// <summary>
  15. /// 添加收件人地址(执行多次即添加多个地址)
  16. /// </summary>
  17. IEmailFactory SetToAddress(params string[] addresses);
  18. /// <summary>
  19. /// 添加抄送人地址(执行多次即添加多个地址)
  20. /// </summary>
  21. IEmailFactory SetCcAddress(params string[] addresses);
  22. /// <summary>
  23. /// 添加附件(执行多次即添加多个附件)
  24. /// </summary>
  25. IEmailFactory SetAttachment(params Attachment[] attachments);
  26.  
  27. void Send();
  28. Task SendAsync();
  29. }

EmailFactory

  1. class EmailFactory : IEmailFactory
  2. {
  3. #region properties
  4. protected string Host { get; set; }
  5. protected int Port { get; set; }
  6. protected string UserName { get; set; }
  7. protected string Password { get; set; }
  8. protected bool EnableSSL { get; set; }
  9. protected int? Timeout { get; set; }
  10. protected string FromAddress { get; set; }
  11. protected string FromDisplayName { get; set; }
  12. protected string Subject { get; set; }
  13. protected string Body { get; set; }
  14. protected IList<string> ToList { get; set; }
  15. protected IList<string> CcList { get; set; }
  16. protected IList<Attachment> Attachments { get; set; }
  17. #endregion
  18.  
  19. #region initial methods
  20. public IEmailFactory SetHost(string host)
  21. {
  22. this.Host = host;
  23. return this;
  24. }
  25. public IEmailFactory SetPort(int port)
  26. {
  27. this.Port = port;
  28. return this;
  29. }
  30. public IEmailFactory SetSSL(bool enableSsl)
  31. {
  32. this.EnableSSL = enableSsl;
  33. return this;
  34. }
  35. public IEmailFactory SetTimeout(int timeout)
  36. {
  37. this.Timeout = timeout;
  38. return this;
  39. }
  40. public IEmailFactory SetUserName(string userName)
  41. {
  42. this.UserName = userName;
  43. return this;
  44. }
  45. public IEmailFactory SetPassword(string password)
  46. {
  47. this.Password = password;
  48. return this;
  49. }
  50. public IEmailFactory SetFromAddress(string address)
  51. {
  52. this.FromAddress = address;
  53. return this;
  54. }
  55. public IEmailFactory SetFromDisplayName(string displayName)
  56. {
  57. this.FromDisplayName = displayName;
  58. return this;
  59. }
  60. public IEmailFactory LoadFromConfigFile()
  61. {
  62. var section = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as System.Net.Configuration.SmtpSection;
  63. this.Host = section.Network.Host;
  64. this.Port = section.Network.Port;
  65. this.EnableSSL = section.Network.EnableSsl;
  66. this.UserName = section.Network.UserName;
  67. this.Password = section.Network.Password;
  68. this.FromAddress = section.From;
  69. return this;
  70. }
  71. public IEmailFactory SetSubject(string subject)
  72. {
  73. this.Subject = subject;
  74. return this;
  75. }
  76. public IEmailFactory SetBody(string body)
  77. {
  78. this.Body = body;
  79. return this;
  80. }
  81. public IEmailFactory SetToAddress(params string[] addresses)
  82. {
  83. if (this.ToList == null) this.ToList = new List<string>();
  84. if (addresses != null)
  85. foreach (var item in addresses)
  86. this.ToList.Add(item);
  87.  
  88. return this;
  89. }
  90. public IEmailFactory SetCcAddress(params string[] addresses)
  91. {
  92. if (this.CcList == null) this.CcList = new List<string>();
  93. if (addresses != null)
  94. foreach (var item in addresses)
  95. this.CcList.Add(item);
  96.  
  97. return this;
  98. }
  99. public IEmailFactory SetAttachment(params Attachment[] attachments)
  100. {
  101. if (this.Attachments == null) this.Attachments = new List<Attachment>();
  102. if (attachments != null)
  103. foreach (var item in attachments)
  104. this.Attachments.Add(item);
  105.  
  106. return this;
  107. }
  108. #endregion
  109.  
  110. public virtual void Send()
  111. {
  112. using (SmtpClient smtp = new SmtpClient(this.Host, this.Port))
  113. {
  114. var message = PreSend(smtp);
  115. smtp.Send(message);
  116. }
  117. }
  118. public virtual async Task SendAsync()
  119. {
  120. using (SmtpClient smtp = new SmtpClient(this.Host, this.Port))
  121. {
  122. var message = PreSend(smtp);
  123. await smtp.SendMailAsync(message);
  124. }
  125. }
  126.  
  127. private MailMessage PreSend(SmtpClient smtp)
  128. {
  129. if (this.UserName != null && this.Password != null)
  130. {
  131. smtp.UseDefaultCredentials = false;
  132. smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
  133. smtp.Credentials = new System.Net.NetworkCredential(this.UserName, this.Password);
  134. }
  135. if (this.Timeout == null)
  136. smtp.Timeout = ;
  137.  
  138. var message = new MailMessage();
  139. message.From = new MailAddress(this.FromAddress, this.FromDisplayName, Encoding.UTF8);
  140.  
  141. if (this.ToList != null)
  142. foreach (var address in this.ToList)
  143. message.To.Add(address);
  144.  
  145. if (this.CcList != null)
  146. foreach (var address in this.CcList)
  147. message.CC.Add(address);
  148.  
  149. if (this.Attachments != null)
  150. foreach (var attachment in this.Attachments)
  151. message.Attachments.Add(attachment);
  152.  
  153. message.Subject = this.Subject;
  154. message.SubjectEncoding = Encoding.UTF8;
  155. message.Body = this.Body;
  156. message.IsBodyHtml = true;
  157. message.BodyEncoding = Encoding.UTF8;
  158. message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
  159. return message;
  160. }
  161. }

EmailWrapper

  1. public class EmailWrapper
  2. {
  3. private static readonly EmailHelper _instance = new EmailHelper();
  4. private EmailHelper() { }
  5.  
  6. public static IEmailFactory Initalize
  7. {
  8. get { return _instance.GetFactory(); }
  9. }
  10. private IEmailFactory GetFactory()
  11. {
  12. return new EmailFactory();
  13. }
  14. }

使用方法:

  1. //同步发送
  2. EmailWrapper.Initalize
  3. .SetHost("smtp.xxxxx.com")
  4. .SetPort()
  5. .SetUserName("xxx@xxxxx.com")
  6. .SetPassword("******")
  7. .SetSSL(false)
  8. .SetFromAddress("xxx@xxxxx.com")
  9. .SetFromDisplayName("Felix")
  10. .SetToAddress("f5.zhang@qq.com", "f5.lee@gmail.com")
  11. .SetCcAddress("f5.chow@yahoo.com")
  12. .SetSubject("会员注册成功")
  13. .SetBody("恭喜你成为会员,为了你的账号安全,请尽快前往安全中心修改登录密码。")
  14. .Send();
  15.  
  16. //异步发送 从CONFIG中加载配置
  17. await EmailWrapper.Initalize
  18. .LoadFromConfigFile()
  19. .SetFromDisplayName("Felix")
  20. .SetToAddress("f5.zhang@qq.com")
  21. .SetToAddress("f5.lee@gmail.com")
  22. .SetToAddress("f5.chow@yahoo.com")
  23. .SetSubject("会员注册成功")
  24. .SetBody("恭喜你成为会员,为了你的账号安全,请尽快前往安全中心修改登录密码。")
  25. .SendAsync();

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

  1. Chilkat----开源站点之VS2010 CKMailMan一个很好的邮件发送开源开发包

    Chilkat 是一个很好的开源站点,有各种开源库. 开发语言主要有Classic ASP •C • C++ • C# • Delphi ActiveX • Delphi DLL • Visual F ...

  2. Spring Boot 邮件发送的 5 种姿势!

    邮件发送其实是一个非常常见的需求,用户注册,找回密码等地方,都会用到,使用 JavaSE 代码发送邮件,步骤还是挺繁琐的,Spring Boot 中对于邮件发送,提供了相关的自动化配置类,使得邮件发送 ...

  3. 测试开发【提测平台】分享11-Python实现邮件发送的两种方法实践

    微信搜索[大奇测试开],关注这个坚持分享测试开发干货的家伙. 按照开发安排,本篇本应该是关于提测页面的搜索和显示实现,怕相似内容疲劳,这期改下内容顺序,将邮件服务的相关的提前,在之前的产品需求和原型中 ...

  4. c# 邮件发送代码分享

    /// <summary> /// 发送邮件方法 /// </summary> /// <param name="sendMail">发送人&l ...

  5. VB.NET的一个邮件发送函数

    ''' <summary> ''' VB.NET邮件发送程序 ''' 还没用在别的服务器,不晓得能不能行,慎用! ''' </summary> ''' <param na ...

  6. 补习系列(12)-springboot 与邮件发送【华为云技术分享】

    目录 一.邮件协议 关于数据传输 二.SpringBoot 与邮件 A. 添加依赖 B. 配置文件 C. 发送文本邮件 D.发送附件 E. 发送Html邮件 三.CID与图片 参考文档 一.邮件协议 ...

  7. 分享一个php邮件库——swiftmailer

    最近看到一个好的php邮件库,与phpmailer作用一样,但性能比phpmailer好,尤其是在处理附件的能力上,发送邮件成功的几率也高. github地址:https://github.com/s ...

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

    今天,给大家分享的是如何在.NET平台中开发“邮件发送”功能.在网上搜的到的各种资料一般都介绍的比较简单,那今天我想比较细的整理介绍下: 1)         邮件基础理论知识 2)         ...

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

    使用phantomjs实现highcharts等报表通过邮件发送(本文仅提供完整解决方案和实现思路,完全照搬不去整理代码无法马上得到效果)   前不久项目组需要将测试相关的质量数据通过每日自动生成报表 ...

随机推荐

  1. 泛函编程(20)-泛函库设计-Further Into Parallelism

    上两节我们建了一个并行运算组件库,实现了一些基本的并行运算功能.到现在这个阶段,编写并行运算函数已经可以和数学代数解题相近了:我们了解了问题需求,然后从类型匹配入手逐步产生题解.下面我们再多做几个练习 ...

  2. Linux命令详解之—cat命令

    cat命令的功能是连接文件或标准输入并打印,今天就为大家介绍下Linux中的cat命令. 更多Linux命令详情请看:Linux命令速查手册 Linux 的cat命令通常用来显示文件内容,也可以用来将 ...

  3. 转载 教你使用PS来制作unity3D随机地形

  4. ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var mysql 启动不了

    ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var mysql 启动不了   ps -A | gr ...

  5. [下载] MultiBeast 6.2.1版,支持10.9 Mavericks。Mac上的驱动精灵,最简单安装驱动的方式。

    下载地址1:http://pan.baidu.com/s/1i3ier9F 下载地址2:http://www.tonymacx86.com/downloads.php?do=cat&id=3 ...

  6. Chrome使用技巧(几个月的心得)

    转用Chrome,不仅仅因为它的插件之丰富,更因为它的响应速度其他浏览器都望尘莫及.接着我就要写写一些心得. 如何最简易地用上谷歌搜索? 1,下载hosts文件:https://pan.baidu.c ...

  7. 移动端H5---页面适配问题详谈(一)

    一.前言 昨天唠叨了哈没用的,今天说点有用的把.先说一下响应式布局吧,我一直认为响应式布局的分项目,一下布局简单得项目做响应式还是可以可以得.例如博客.后台管理系统等.但是有些会认为响应式很牛逼,尤其 ...

  8. ASP.NET MVC 微信公共平台开发之获取用户消息并处理

    ASP.NET MVC 微信公共平台开发 获取用户消息并处理 获取用户消息 用户发送的消息是在微信服务器发送的一个HTTP POST请求中包含的,获取用户发送的消息要从POST请求的数据流中获取 微信 ...

  9. ogrinfo使用

    简介 orginfo是OGR模块中提供的一个重要工具,用于读取地图文件中记录,可以指定筛选条件(按字段.sql.矩形范围) 使用方式 命令行参数 Usage: ogrinfo [--help-gene ...

  10. iOS设计模式之单例模式

    单例模式 基础理解 所有类都有构造方法,不编码则系统默认生成空的构造方法,若有显示定义的构造方法,默认的构造方法就会失效. 单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全 ...