本文實例講述了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#程序設計有所幫助。