Embed a picture in a message by code

Source: Internet
Author: User
Tags mailmessage smtpclient

In a development requirement, you need to embed a picture in the message and send it out.

The normal message sending code (C #) is as follows:

MailMessage mail = new MailMessage (from, to, subject, emailbody);

If you need mail support for HTML, you need to set isbodyhtml to true:mail.IsBodyHtml = true;

1. The first way to think of it is to add tag in Emailbody, but if the user who receives the message cannot access the resource link in SCR, it will cause the picture to be inaccessible.

2. The second way to find out is that the pictures in Data:image/png;base64,emailbody can be displayed in the browser, but Outlook is blocked and cannot be viewed. The code is as follows:


String base64str = convert.tobase64string (File.readallbytes (@ "C:\Temp\test.png"));

3. The third approach is to use "CID:", which basically satisfies the requirements. The code is as follows:

Linkedresource inline = new Linkedresource (@ "C:\Temp\test.png", MediaTypeNames.Image.Jpeg);
Inline. ContentId = Guid.NewGuid (). ToString ();
String htmlBody = @ "AlternateView AlternateView = alternateview.createalternateviewfromstring (HtmlBody, NULL, MediaTypeNames.Text.Html) ;
ALTERNATEVIEW.LINKEDRESOURCES.ADD (inline);

MailMessage mail = new MailMessage (from, to);
Mail. Subject = "Subject";
Mail. Isbodyhtml = true;
Mail. Alternateviews.add (AlternateView);

SmtpClient smtp = new SmtpClient ("127.0.0.1");
Smtp. Send (mail);

There are two concepts Linkedresource and AlternateView in the implementation.

Linkresouce represents an embedded external resource in an e-mail attachment, compared to a slice. However, such resources are not displayed as attachments in the message. For accessories you need to use attachment

AlternateView can specify a different rendition of an e-mail message.

Reference:

Http://stackoverflow.com/questions/18358534/send-inline-image-in-email

https://sendgrid.com/blog/embedding-images-emails-facts/

Embed a picture in a message by code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.