剛才有網友問是不是可以非同步發送郵件,我測試完全沒有問題。注意這裡用到了SendCompleted事件和SendAsync方法。
代碼如下,代碼簡單不做太多解釋,不懂得看我上一篇文章。
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Net;
6 using System.Net.Mail;
7 using System.Threading;
8
9 namespace MailTest
10 {
11 class Program
12 {
13 //阻塞線程。
14 private static AutoResetEvent _event = new AutoResetEvent(false);
15
16 static void Main(string[] args)
17 {
18 string user = "zhangsan";
19 string password = "zhangsan";
20 //
21 string host = "smtp.gmail.com";
22 //
23 string mailAddress = "zhangsan@gmail.com";
24 string ToAddress = "zhangsan@hotmail.com";
25 //
26
27 SmtpClient smtp = new SmtpClient(host);
28 smtp.EnableSsl = true; //開啟安全連線。
29 smtp.Credentials = new NetworkCredential(user, password); //建立使用者憑證
30 smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //使用網路傳送
31 //建立郵件
32 MailMessage message = new MailMessage(mailAddress, ToAddress, "Test", "This is a Test Message");
33 //註冊事件
34 smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);
35 smtp.SendAsync(message, "TheObjectCompletedUse");
36 //等待完成。
37 _event.WaitOne();
38 Console.WriteLine("Main method end");
39 }
40
41 private static void smtp_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
42 {
43 Console.WriteLine((string)e.UserState);
44 _event.Set();
45 }
46 }
47 }
。很簡單吧。代碼測試完全沒有問題,注意替換成真正有效GMAIL賬戶。
下載:下載