>直接使用C#的电子邮件正文中嵌入图像需要一种特定的方法,作为标准电子邮件附件仅作为占位符显示。 此精制C#代码演示了如何正确嵌入图像:
<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>
>和AlternateView
类。 LinkedResource
>将图像文件与唯一的LinkedResource
相关联。然后在ContentId
中的html引用此AlternateView
,以确保显示图像。 此方法可防止常见的“红色X”占位符经常在附加的图像中看到。 切记用您的实际数据替换占位符值。ContentId
以上是如何使用C#将图像直接嵌入电子邮件的正文中?的详细内容。更多信息请关注PHP中文网其他相关文章!