Home >Backend Development >C++ >How Can I Embed Images Directly into the Body of an Email Using C#?
Directly embedding images within the body of an email using C# requires a specific approach, as standard email attachments only display as placeholders. This refined C# code demonstrates how to correctly embed images:
<code class="language-csharp">MailMessage mailWithImg = GetMailWithImg(); MySMTPClient.Send(mailWithImg); // Ensure MySMTPClient is properly configured private MailMessage GetMailWithImg() { MailMessage mail = new MailMessage(); mail.IsBodyHtml = true; mail.AlternateViews.Add(GetEmbeddedImage("c:/image.png")); // Replace with your image path mail.From = new MailAddress("yourAddress@yourDomain"); // Replace with your email address mail.To.Add("recipient@hisDomain"); // Replace with recipient's email address mail.Subject = "yourSubject"; // Replace with your email subject return mail; } private AlternateView GetEmbeddedImage(String filePath) { LinkedResource res = new LinkedResource(filePath); res.ContentId = Guid.NewGuid().ToString(); string htmlBody = $"<img src=\"cid:{res.ContentId}\" />"; // Note the escaped quotes AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html); alternateView.LinkedResources.Add(res); return alternateView; }</code>
This code leverages the AlternateView
and LinkedResource
classes. LinkedResource
associates the image file with a unique ContentId
. The HTML within AlternateView
then references this ContentId
, ensuring the image is displayed inline. This method prevents the common "red x" placeholder often seen with attached images. Remember to replace placeholder values with your actual data.
The above is the detailed content of How Can I Embed Images Directly into the Body of an Email Using C#?. For more information, please follow other related articles on the PHP Chinese website!