使用SmtpClient发送带图片的邮件的代码实现

本文是自己的一个coding记录,希望同时能对您有帮助。

以下代码的主要目的是将HTML作为邮件body发送。在发送的过程中,必须将<img src="url">这个传统的显示方式改为<img src="cid:imageId">。然后使用image的url创建一个LinkedResource对象。然后将LinkedResource对象的ContentId属性设置为对应的imageId.

 1  private void SendEmail(string from, string to, string cc, string subject, string body)
2 {
3 //找出HTML BODY中的<IMG>标签,保存标签的URL,修改src属性为"cid:imageid"。保存imageid与<img>标签原本的url对应关系
4 Dictionary<string, string> resDic = new Dictionary<string, string>();
5 Match imgMatch = Regex.Match(body, "<img[^>]*>", RegexOptions.IgnoreCase);
6 int i = 0;
7
8 while (imgMatch.Success)
9 {
10 Match srcMatch = Regex.Match(imgMatch.Value, "src(\\s*)=(\\s*)(\"|')[^\"]*\\3", RegexOptions.IgnoreCase);
11 if (srcMatch.Length > 0)
12 {
13 string cid = "ImageCid" + i.ToString();
14 int index = srcMatch.Value.IndexOf("\"") == -1 ? srcMatch.Value.IndexOf("'") : srcMatch.Value.IndexOf("\"");
15 string src = srcMatch.Value.Substring(index + 1, srcMatch.Value.Trim().Length - index - 2);
16 string cidImg = Regex.Replace(imgMatch.Value, "src(\\s*)=(\\s*)(\"|')[^\"]*\\3", string.Format("src=\"cid:{0}\"", cid));
17 body = Regex.Replace(body, imgMatch.Value, cidImg);
18 resDic.Add(cid, src);
19 }
20 imgMatch = imgMatch.NextMatch();
21 i++;
22 }
23
24 //根据修改后的html body创建一个AlertnateView对象。遍历上面保存的URL,获取图片的stream。
25 AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
26 if (resDic.Count > 0)
27 {
28 foreach (KeyValuePair<string, string> pair in resDic)
29 {
30 System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(pair.Value);
31 request.UseDefaultCredentials = true;
32 System.Net.WebResponse response = request.GetResponse();
33 System.IO.Stream stream = request.GetResponse().GetResponseStream();
34 System.IO.MemoryStream ms = new System.IO.MemoryStream();
35 byte[] bts = new byte[250];
36 byte[] nbytes = new byte[512];
37 int nReadSize = 0;
38 nReadSize = stream.Read(nbytes, 0, 512);
39 while (nReadSize > 0)
40 {
41 ms.Write(nbytes, 0, nReadSize);
42 nReadSize = stream.Read(nbytes, 0, 512);
43 }
44 ms.Write(nbytes, 0, nReadSize);
45 ms.Position = 0;
46 LinkedResource linkedRes = new LinkedResource(ms, System.Net.Mime.MediaTypeNames.Image.Jpeg);
47 linkedRes.ContentId = pair.Key;//与<img src="cid:imageID">中imageID对应
48 htmlBody.LinkedResources.Add(linkedRes);
49 }
50 }
51
52
53
54 //发送邮件send email
55 System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
56 mail.From = new MailAddress(from);
57 mail.To.Add(to);
58 if (!string.IsNullOrEmpty(cc))
59 {
60 mail.CC.Add(cc);
61 }
62 mail.Subject = subject;
63 mail.AlternateViews.Add(htmlBody);
64
65 System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(this.WebApplication.OutboundMailServiceInstance.Server.Address);
66 smtp.UseDefaultCredentials = (smtp.Credentials == null);
67 smtp.Send(mail);
68
69 }
70
71 }

  

原文地址:https://www.cnblogs.com/snailJuan/p/2136451.html