C#中使用SmtpClient发送邮件与图片内嵌 [英] C# sending mails with images inline using SmtpClient

查看:516
本文介绍了C#中使用SmtpClient发送邮件与图片内嵌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SmtpClient(),您可以将附件添加到您的邮件,但是如果你想什么使邮件打开时,而不是安装它的形象出现?

SmtpClient() allows you to add attachments to your mails, but what if you wanna make an image appear when the mail opens, instead of attaching it?

我记得,它可以用约4 code线做的,但我不记得如何,我无法找到它的MSDN站点。

As I remember, it can be done with about 4 lines of code, but I don't remember how and I can't find it on the MSDN site.

编辑:我不使用网站或任何东西,甚至不是一个IP地址。图像(S)位于一个硬盘。时发送的,它们应该是邮件的一部分。所以,我想我可能会想用一个标签......但我也不太清楚,因为我的电脑没有广播。

I'm not using a website or anything, not even an IP address. The image(s) are located on a harddrive. When sent, they should be part of the mail. So, I guess I might wanna use an tag... but I'm not too sure, since my computer isn't broadcasting.

推荐答案

这是经常提到的一个解决方案是将图像添加为附件来的邮件,然后参考:使用 CID引用它在HTML mailbody。

One solution that is often mentioned is to add the image as an Attachment to the mail, and then reference it in the HTML mailbody using a cid: reference.

然而,如果你使用 LinkedResources 集合相反,内嵌图像仍会出现就好,但不显示为其他附件的邮件。 这就是我们希望发生,所以这就是我在这里做的:

However if you use the LinkedResources collection instead, the inline images will still appear just fine, but don't show as additional attachments to the mail. That's what we want to happen, so that's what I do here:

using (var client = new SmtpClient())
{
    MailMessage newMail = new MailMessage();
    newMail.To.Add(new MailAddress("you@your.address"));
    newMail.Subject = "Test Subject";
    newMail.IsBodyHtml = true;

    var inlineLogo = new LinkedResource(Server.MapPath("~/Path/To/YourImage.png"));
    inlineLogo.ContentId = Guid.NewGuid().ToString();

    string body = string.Format(@"
            <p>Lorum Ipsum Blah Blah</p>
            <img src=""cid:{0}"" />
            <p>Lorum Ipsum Blah Blah</p>
        ", inlineLogo.ContentId);

    var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
    view.LinkedResources.Add(inlineLogo);
    newMail.AlternateViews.Add(view);

    client.Send(newMail);
}

注意::该解决方案添加了一个 AlternateView 你的类型的 MAILMESSAGE 的text / html 。为了完整起见,你也应该添加一个 AlternateView 类型文本/纯,包含电子邮件的一个纯文本版本非HTML的邮件客户端。

NOTE: This solution adds an AlternateView to your MailMessage of type text/html. For completeness, you should also add an AlternateView of type text/plain, containing a plain text version of the email for non-HTML mail clients.

这篇关于C#中使用SmtpClient发送邮件与图片内嵌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆