Introduction
Sending and receiving emails is a daily task for almost every professional, and programmers are not different. Sending emails and attachment is considered a trivial task, and all programming platforms support this feature.
Background
You can send an email with images as external links, but most email clients block external links. There is another way around to send images as part of an email.
Using the code
The following code is self explanatory. Here, we go:
- Create a string that contains the HTML message to send.
- Create an
AlternateViewobject for supporting the HTML. - Create a
LinkedResourceobject for the image to send. - Add a
LinkedResourceobject to theAlternateViewobject. - Create a
Mailmesasgeobject and set itsTo,From, andSubjectproperties. - Add an
AlternateViewobject to theMailMessageobject. - Create an
SmtpClientobject and send theMailMessageobject.
using System.Net.Mail;
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);
// Add the alternate views instead of using MailMessage.Body
MailMessage m = new MailMessage();
m.AlternateViews.Add(avHtml);
// Address and send the message
m.From = new MailAddress("rizwan@dotnetplayer.com", "Rizwan Qureshi");
m.To.Add(new MailAddress("shayan@dotnetplayer.com", "Shayan Qureshi"));
m.Subject = "A picture using alternate views";
SmtpClient client = new SmtpClient("smtp.dotnetplayer.com");
client.Send(m);
本文介绍如何使用C#编程语言通过SMTP服务发送包含内联图片的HTML格式邮件。具体步骤包括创建HTML消息体、设置AlternateView与LinkedResource对象来嵌入图片,并通过SmtpClient对象发送邮件。
948

被折叠的 条评论
为什么被折叠?



