服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#使用系统方法发送异步邮件完整实例

C#使用系统方法发送异步邮件完整实例

2021-11-30 13:14HTL C#

这篇文章主要介绍了C#使用系统方法发送异步邮件实现方法,结合完整实例形式分析了C#异步调用与邮件发送的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了c#使用系统方法发送异步邮件。分享给大家供大家参考,具体如下:

项目背景:

最近在对几年前的一个项目进行重构,发现发送邮件功能需要一定的时间来处理,而由于发送是同步的因此导致在发送邮件时无法执行后续的操作

实际上发送邮件后只需要将发送结果写入系统日志即可对其他业务没有任何影响,因此决定将发送邮件操作更改为异步的

由于使用的是c#的邮件类库,而c#本身已经提供了异步发送的功能即只需要将send方法更改为sendasync即可,更改方法名并不难但发送后再写入日志就有点难了

因为项目中发送邮件是单独的组件,所以我不可能在发送邮件类库中直接添加写入日志操作(不在同一个类库,网络和msdn上的例子都是同一组件下)

但c#可以使用委托将方法作为参数来传递的,因此我就可以在发送邮件的方法中添加一个回调方法,在异步发送邮件后再执行回调方法即可

完整代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/******************************************************************
 * 创建人:htl
 * 说明:c# 发送异步邮件demo
 *******************************************************************/
using system;
using system.net.mail;
namespace sendasyncemailtest
{
  class program
  {
    const string dateformat = "yyyy-mm-dd :hh:mm:ss:ffffff";
    static void main(string[] args)
    {
      console.writeline("开始异步发送邮件,时间:" + datetime.now.tostring(dateformat));
      new mailhelper().sendasync("send async email test", "this is send async email test", "huangyuan413026@163.com", emailcompleted);
      console.writeline("邮件正在异步发送,时间:" + datetime.now.tostring(dateformat));
      console.readkey();
      console.writeline();
    }
    /// <summary>
    /// 邮件发送后的回调方法
    /// </summary>
    /// <param name="message"></param>
    static void emailcompleted(string message)
    {
      //延时1秒
      system.threading.thread.sleep(1000);
      console.writeline();
      console.writeline("邮件发送结果:\r\n" + (message == "true" ? "邮件发送成功" : "邮件发送失败") + ",时间:" + datetime.now.tostring(dateformat));
      //写入日志
    }
  }
  /// <summary>
  /// 发送邮件类
  /// </summary>
  public class mailhelper
  {
    public delegate int methoddelegate(int x, int y);
    private readonly int smtpport = 25;
    readonly string smtpserver = "smtp.baidu.com";
    private readonly string username = "support@baidu.com";
    readonly string pwd = "baidu.com";
    private readonly string authorname = "baidu";
    public string subject { get; set; }
    public string body { get; set; }
    public string tos { get; set; }
    public bool enablessl { get; set; }
    mailmessage getclient
    {
      get
      {
        if (string.isnullorempty(tos)) return null;
        mailmessage mailmessage = new mailmessage();
        //多个接收者
        foreach (string _str in tos.split(','))
        {
          mailmessage.to.add(_str);
        }
        mailmessage.from = new system.net.mail.mailaddress(username, authorname);
        mailmessage.subject = subject;
        mailmessage.body = body;
        mailmessage.isbodyhtml = true;
        mailmessage.bodyencoding = system.text.encoding.utf8;
        mailmessage.subjectencoding = system.text.encoding.utf8;
        mailmessage.priority = system.net.mail.mailpriority.high;
        return mailmessage;
      }
    }
    smtpclient getsmtpclient
    {
      get
      {
        return new smtpclient
        {
          usedefaultcredentials = false,
          credentials = new system.net.networkcredential(username, pwd),
          deliverymethod = system.net.mail.smtpdeliverymethod.network,
          host = smtpserver,
          port = smtpport,
          enablessl = enablessl,
        };
      }
    }
    //回调方法
    action<string> actionsendcompletedcallback = null;
    ///// <summary>
    ///// 使用异步发送邮件
    ///// </summary>
    ///// <param name="subject">主题</param>
    ///// <param name="body">内容</param>
    ///// <param name="to">接收者,以,分隔多个接收者</param>
    //// <param name="_actincompletedcallback">邮件发送后的回调方法</param>
    ///// <returns></returns>
    public void sendasync(string subject, string body, string to, action<string> _actincompletedcallback)
    {
      if (string.isnullorempty(to)) return;
      tos = to;
      smtpclient smtpclient = getsmtpclient;
      mailmessage mailmessage = getclient;
      if (smtpclient == null || mailmessage == null) return;
      subject = subject;
      body = body;
      enablessl = false;
      //发送邮件回调方法
      actionsendcompletedcallback = _actincompletedcallback;
      smtpclient.sendcompleted += new sendcompletedeventhandler(sendcompletedcallback);
      try
      {
        smtpclient.sendasync(mailmessage, "true");//异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
      }
      catch (exception e)
      {
        throw new exception(e.message);
      }
      finally
      {
        smtpclient = null;
        mailmessage = null;
      }
    }
    /// <summary>
    /// 异步操作完成后执行回调方法
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void sendcompletedcallback(object sender, system.componentmodel.asynccompletedeventargs e)
    {
      //同一组件下不需要回调方法,直接在此写入日志即可
      //写入日志
      //return;
      if (actionsendcompletedcallback == null) return;
      string message = string.empty;
      if (e.cancelled)
      {
        message = "异步操作取消";
      }
      else if (e.error != null)
      {
        message = (string.format("userstate:{0},message:{1}", (string)e.userstate, e.error.tostring()));
      }
      else
        message = (string)e.userstate;
      //执行回调方法
      actionsendcompletedcallback(message);
    }
  }
}

运行效果图如下:

C#使用系统方法发送异步邮件完整实例

希望本文所述对大家c#程序设计有所帮助。

延伸 · 阅读

精彩推荐
  • C#C#设计模式之Visitor访问者模式解决长隆欢乐世界问题实例

    C#设计模式之Visitor访问者模式解决长隆欢乐世界问题实例

    这篇文章主要介绍了C#设计模式之Visitor访问者模式解决长隆欢乐世界问题,简单描述了访问者模式的定义并结合具体实例形式分析了C#使用访问者模式解决长...

    GhostRider9502022-01-21
  • C#Unity3D实现虚拟按钮控制人物移动效果

    Unity3D实现虚拟按钮控制人物移动效果

    这篇文章主要为大家详细介绍了Unity3D实现虚拟按钮控制人物移动效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一...

    shenqingyu060520232410972022-03-11
  • C#深入解析C#中的交错数组与隐式类型的数组

    深入解析C#中的交错数组与隐式类型的数组

    这篇文章主要介绍了深入解析C#中的交错数组与隐式类型的数组,隐式类型的数组通常与匿名类型以及对象初始值设定项和集合初始值设定项一起使用,需要的...

    C#教程网6172021-11-09
  • C#WPF 自定义雷达图开发实例教程

    WPF 自定义雷达图开发实例教程

    这篇文章主要介绍了WPF 自定义雷达图开发实例教程,本文介绍的非常详细,具有参考借鉴价值,需要的朋友可以参考下...

    WinterFish13112021-12-06
  • C#C#裁剪,缩放,清晰度,水印处理操作示例

    C#裁剪,缩放,清晰度,水印处理操作示例

    这篇文章主要为大家详细介绍了C#裁剪,缩放,清晰度,水印处理操作示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    吴 剑8332021-12-08
  • C#C# 实现对PPT文档加密、解密及重置密码的操作方法

    C# 实现对PPT文档加密、解密及重置密码的操作方法

    这篇文章主要介绍了C# 实现对PPT文档加密、解密及重置密码的操作方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下...

    E-iceblue5012022-02-12
  • C#C#实现XML文件读取

    C#实现XML文件读取

    这篇文章主要为大家详细介绍了C#实现XML文件读取的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    Just_for_Myself6702022-02-22
  • C#C#通过KD树进行距离最近点的查找

    C#通过KD树进行距离最近点的查找

    这篇文章主要为大家详细介绍了C#通过KD树进行距离最近点的查找,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    帆帆帆6112022-01-22