第一次使用這種方式發郵件呵呵,就比如拿我的Live郵箱往QQ郵箱上發一封郵件。
使用SmtpClient發送郵件的步驟就不講了,在網上你可以找到太多的資料了,這裡說一些需要注意的地方:
如果郵件的內容是HTML,設定MailMessage.IsBodyHtml為True,這樣郵件才能夠被正確以HTML形式讀取。
在HTML中引用資源使用cid:xxx,xxx是附件的ContentId屬性。同時也可以在MailMessage中的AlternateViews中加入AlternateView來指定電子郵件內容的不同格式。通過AlternativeView的LinkedResources來加入引用檔案。引用也是通過LinkedResource的ContentId來設定的。事實上這個ContentId屬性是來自AttachmentBase類型,而Attachment,AlternateView和LinkedResource類型都繼承與這個類:
另外郵件的內容,主題,位址名稱如果包含某些非ASCII字元的話應該指定一個編碼,因為預設編碼是ASCII。
最後某些SMTP伺服器可能不支援SSL傳輸,因此SmtpClient的EnableSsl只能為false(否則會有異常拋出)。
代碼:
using System;
using System.Text;
using System.Net;
using System.Net.Mime;
using System.Net.Mail;
namespace Mgen
{
class Program
{
static void Main()
{
//代碼中的某些資訊(如郵箱和密碼)已用xxx代替,因此如果編譯代碼,請先替換成有效資料!
using (var smtp = new SmtpClient())
using (var mail = new MailMessage("xxx@live.com", "xxx@qq.com"))
{
//映像附件
var attach = new Attachment(@"D:\a.jpg", MediaTypeNames.Image.Jpeg);
//設定ContentId
attach.ContentId = "pic";
//ZIP附件
var attach2 = new Attachment(@"D:\b.zip", "application/x-zip-compressed");
mail.Attachments.Add(attach);
mail.Attachments.Add(attach2);
//標題和內容,注意設定編碼,因為預設編碼是ASCII
mail.Subject = "你好";
mail.SubjectEncoding = Encoding.UTF8;
//HTML內容
mail.Body = "<img src=\"cid:pic\"/><p>來自Mgen。</p>";
mail.BodyEncoding = Encoding.UTF8;
//指示改電子郵件內容是HTML格式
mail.IsBodyHtml = true;
//SMTP設定(根據郵箱類型設定,這裡是Live Mail的SMTP伺服器位址)
smtp.Host = "smtp.live.com";
smtp.UseDefaultCredentials = false;
//某些SMTP伺服器可能不支援SSL,會拋出異常
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("xxx@live.com", "xxx");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
//發送
smtp.Send(mail);
}
}
}
}
最後在QQ郵箱中瀏覽接收到的郵件: