C# 70-536 Chapter 15 Mail

C# 70-536 Chapter 15 Mail

在System.Net.Mail,提供了建立Email的物件的方式。

先利用MailMessage建立郵件後,利用SmtpClient寄送。

MailMessage mail = new MailMessage();
mail.From = new MailAddress("Mary@xxx.com", "Mary");
mail.To.Add(new MailAddress("John@xxxxx.com", "John"));
mail.Subject = "This is a Test";
mail.Body = "Mail's Body";
mail.BodyEncoding = Encoding.UTF8;
mail.IsBodyHtml = true; //html編碼

// mail.CC 副本
// mail.BCC 密件副本
// mail.DeliveryNotificationOptions 通知狀態 OnSuccess, OnFailure, Delay, None, Never
// mail.ReplyTo 指定回覆地址

//附加檔案
Stream sr = new FileStream(@"C:\Boot.ini", FileMode.Open, FileAccess.Read);
mail.Attachments.Add(new Attachment(sr, "myfile.txt", MediaTypeNames.Application.Octet));

//透過smtp寄件
SmtpClient sc = new SmtpClient("smpt.xx.xx");
sc.Send(mail);

如果無法確保對方收到電子郵件是否可以以html方式開啟,可以利用AlternateView,指定一個電子郵件的不同格式副本。同時包含html及純文字格式。

//純文字
AlternateView plainView = AlternateView.CreateAlternateViewFromString("You must use an e-mail client that supports HTML messages", null, "text/plain");

//HTML
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<html><body><h1>My Message</h1><br>This is an HTML message.</body></html>", null, "text/html");

mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);

同時還可以利用LinkedResource加入圖檔:

 

string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:Pic1\"></body></html>"; 
AlternateView avHtml = AlternateView.CreateAlternateViewFromString 
(htmlBody, null, MediaTypeNames.Text.Html); 
 
// Create a LinkedResource object for each embedded image 
LinkedResource pic1 = new LinkedResource("pic.jpg", MediaTypeNames.Image.Jpeg); 
pic1.ContentId = "Pic1"; 
avHtml.LinkedResources.Add(pic1); 

 

在img裡面宣告的 cid:Pic1,會參考到LinkedResource內指定的ContentId,每個LinkedResource都應該要有一個獨立的ContentId。

有些SMTP Server會要求驗證使用者身份,或是使用SSL加密:

// 驗證
SmtpClient sc = new SmtpClient("smtp.contoso.com"); 
client.Credentials = new NetworkCredential("user", "password");

// 加密
sc.EnableSsl = true

非同步寄送:SmtpClient.SendAsync

取消非同步寄送:SmtpClient.SendAsyncCancel

完成非同步寄送事件:SmtpClient.SendCompleted