dotnet中用SmtpClient來發送郵件,以前的System.Web.Mail已經不推薦使用了,新的方法在命名空間System.Net.Mail中。
涉及到的命名空間有:
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
下面舉兩個簡單的例子,是我測試時候用的:
//同步發送郵件 SmtpClient client = new SmtpClient(); //smtp server address client.Host = "mail1.ufida.com"; //smtp server port client.Port = 25; //connect timeout client.Timeout = 5000; //mail account client.Credentials = new NetworkCredential("***@ufida.com", "***");//登入郵箱的賬戶和密碼 //simple send client.Send("***@ufida.com","***@qq.com","subject","msg");//寄件者,收件者,主題,本文
這樣一封簡單的郵件就發送完成,其中client.Send()方法是同步發送郵件,簡單的說就是單線程。
也可以使用非同步發送郵件的方法,在郵件發送完成的時候,會返回一個SendCompletedEventHandler事件。
調用郵件發送的按鈕事件如下:
private void button2_Click(object sender, EventArgs e) { //非同步發送郵件 //create mail message MailAddress from = new MailAddress("***@ufida.com","UF"); MailAddress to = new MailAddress("***@qq.com", "QQ"); MailMessage mail = new MailMessage(from, to); //add more to添加多個收件者 MailAddress to2 = new MailAddress("***@qq.com", "QQ"); mail.To.Add(to2); //add more cc添加抄送 MailAddress cc = new MailAddress("***@qq.com", "QQ"); mail.CC.Add(cc); //add more bcc添加密送 MailAddress bcc = new MailAddress("***@qq.com", "QQ"); mail.Bcc.Add(bcc); mail.Subject = "subject"; mail.Body = "msg"; mail.BodyEncoding = System.Text.Encoding.UTF8;//本文編碼格式 mail.IsBodyHtml = false;//本文是否為HTML郵件 //create attachment by stream 以檔案流方式讀取附件並發送 //System.IO.FileInfo file = new System.IO.FileInfo(@"E:\mycos_myjob_issue003.pdf"); //Attachment att = new Attachment(file.OpenRead(), MediaTypeNames.Application.Pdf); //or add file或者直接指定附件檔案的絕對路徑 //Attachment att = new Attachment(@"E:\mycos_myjob_issue003.pdf", MediaTypeNames.Application.Octet); //mail.Attachments.Add(att); //create account NetworkCredential account = new NetworkCredential("***@ufida.com", "***"); SmtpClient client = new SmtpClient(); //smtp server address client.Host = "mail1.ufida.com"; //ssl是否為ssl加密 client.EnableSsl = false; //smtp server port client.Port = 25; //connect timeout client.Timeout = 5000; //mail account client.Credentials = account; client.SendCompleted += new SendCompletedEventHandler(MailSendCompleted);//這裡註冊郵件發送完成的事件回應程式法 //simple send非同步發送 client.SendAsync(mail, "testMail");//第二個參數會被傳入事件SendCompletedEventHandler中,所以可以將郵件相關的資訊放到第二個參數中,這樣在郵件發送完成的響應事件方法中,就可以判斷出完成發送的是哪封郵件了。 }
下面是郵件發送完成的事件回應程式法
public void MailSendCompleted(object sender, AsyncCompletedEventArgs e) { if (e.Cancelled) { label1.Text = "cancel"; } else if (e.Error != null) { label1.Text = "error" + e.Error.Message; } else { label1.Text = "completed" + e.UserState.ToString();//UserState是client.SendAsync()方法中的第二個參數 } }
這些發送郵件的類使用起來比較簡單,所以功能也很簡單。比如想在郵件發送之前計算郵件的大小(一般是本文內容大小 加上 附件大小),或者是擷取郵件發送中的進度等這些功能是沒有的,或者說我沒有找到有,而且我個人也認為這種封裝程度高的類,使用方便,就是靈活性不夠。