文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>c#编程指南(八) 异步C#通过GMAIL发送邮件

c#编程指南(八) 异步C#通过GMAIL发送邮件

时间:2010-08-19  来源:香山飘雪

 

刚才有网友问是不是可以异步发送邮件,我测试完全没有问题。注意这里用到了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 = "[email protected]";
24 string ToAddress = "[email protected]";
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账户。

 

下载:下载

 

 

 

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载