C#—发邮件方法
前几天,有个系统需要增加一个发邮件的功能,于是写了一个方法,如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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;
作者:Statmoon
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。