c#編程指南(八) 非同步C#通過GMAIL發送郵件

來源:互聯網
上載者:User

 

剛才有網友問是不是可以非同步發送郵件,我測試完全沒有問題。注意這裡用到了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賬戶。

 

下載:下載

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.