C#—发邮件方法

前几天,有个系统需要增加一个发邮件的功能,于是写了一个方法,如下:

View Code
 1 /// <summary>
2 ///
3 /// </summary>
4 /// <param name='clientHost'>邮件服务器地址</param>
5 /// <param name='emailAddress'>发件人邮箱地址</param>
6 /// <param name='receiveAddress'>收件人邮箱地址</param>
7 /// <param name='userName'>发件人邮箱用户名</param>
8 /// <param name='password'>发件人邮箱密码</param>
9 /// <param name="subject">邮件主题</param>
10 /// <param name="body">邮件正文</param>
11 private void SendEmail(string clientHost, string emailAddress, string receiveAddress,
12 string userName, string password, string subject, string body)
13 {
14 MailMessage mail = new MailMessage();
15 mail.From = new MailAddress(emailAddress);
16 mail.To.Add(new MailAddress(receiveAddress));
17 mail.Subject = subject;
18 mail.Body = body;
19 mail.IsBodyHtml = true;
20 mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
21
22 SmtpClient client = new SmtpClient();
23 client.Host = clientHost;
24 client.Credentials = new NetworkCredential(userName, password);
25 client.DeliveryMethod = SmtpDeliveryMethod.Network;
26 try
27 {
28 client.Send(mail);
29 }
30 catch (Exception ex)
31 {
32 // Get ex.Message and do something
33 }
34 }

此方法需要引用两个命名空间:

1 using System.Net.Mail;
2 using System.Net;



 

posted @ 2011-12-11 19:19  Statmoon  阅读(359)  评论(0编辑  收藏  举报