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

如何将图像直接嵌入到电子邮件正文中?

Patricia Arquette
Patricia Arquette原创
2025-01-25 01:46:10335浏览

How Can I Embed Images Directly into the Body of My Emails?

使用嵌入图像改进您的电子邮件

将图像直接添加到电子邮件正文中可以显着增强可读性和用户参与度。 虽然以前的方法可能存在问题,但此解决方案利用 AlternateView 类将图像作为资源无缝嵌入到您的 HTML 电子邮件中。

这是更新后的代码:

<code class="language-csharp">MailMessage mailWithImg = GetMailWithImg();
MySMTPClient.Send(mailWithImg); //* Remember to configure your SMTPClient beforehand!

private MailMessage GetMailWithImg() {
    MailMessage mail = new MailMessage();
    mail.IsBodyHtml = true;
    mail.AlternateViews.Add(GetEmbeddedImage("c:/image.png"));
    mail.From = new MailAddress("yourAddress@yourDomain");
    mail.To.Add("recipient@hisDomain");
    mail.Subject = "Your 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}\"></img>"; //Using string interpolation for clarity
    AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
    alternateView.LinkedResources.Add(res);
    return alternateView;
}</code>

这种精炼的代码可确保您的图像在电子邮件中内联显示,无需单独的附件,并为收件人提供更流畅的阅读体验。 请记住将 "c:/image.png" 和电子邮件地址替换为您的实际文件路径和地址。

以上是如何将图像直接嵌入到电子邮件正文中?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn