首页 > 后端开发 > C++ > 如何使用C#将图像直接嵌入电子邮件的正文中?

如何使用C#将图像直接嵌入电子邮件的正文中?

Barbara Streisand
发布: 2025-01-25 01:27:11
原创
490 人浏览过

How Can I Embed Images Directly into the Body of an Email Using C#?

>将图像嵌入带有C

的电子邮件体中

>直接使用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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板