发送邮件嵌入图片

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:

  1. Create a string that contains the HTML message to send.
  2. Create an AlternateView object for supporting the HTML.
  3. Create a LinkedResource object for the image to send.
  4. Add a LinkedResource object to the AlternateView object.
  5. Create a Mailmesasge object and set its ToFrom, and Subject properties.
  6. Add an AlternateView object to the MailMessage object.
  7. Create an SmtpClient object and send the MailMessage object.
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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值