无法使用MailKit将图像嵌入电子邮件中

问题描述 投票:1回答:1

此问题已经提出,并在SO上回答了多个地方,特别是在这里:Issue with Gmail - Embedded images using MailKit并处理了我的确切查询,但答案似乎不适用于我的情况。

我已经尝试构建一个简单的邮件程序,将图像嵌入HTML电子邮件中,但是在多个客户端中,所有图像仍最终以附件的形式出现。

我怀疑是我处理图片附件(一个.gif和几个.png)的方式有问题:

// Add pictures to embedded resources and replace links to pictures in the message
foreach (string imgpath in ImgPaths)
{
    var image = builder.LinkedResources.Add(imgpath);
    image.ContentId = MimeUtils.GenerateMessageId();
    image.ContentDisposition = new ContentDisposition() { Disposition = ContentDisposition.Inline };
    HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
}
builder.HtmlBody = HtmlFormat;
message.Body = builder.ToMessageBody();

我可以从电子邮件中看到(例如,在Gmail中收到的电子邮件,确实显示图像被列为:

src="images/cid:TPSXHQUDSAU4.JJRKUIEGLTZ5@Loralei"

所有图像都作为附件附加在我尝试过的两个客户端(gmail和roundcube)中。我已经遍历了您的教程,并在此处查看了所有内容:https://stackoverflow.com/search?q=Mailkit+Embed可悲的是,我似乎找不到我的错误。希望@jstedfast可以看到我在哪里犯了错误?

UPDATE

正如@jstedfast所提到的,更正后的代码应该是(就我而言):

foreach (string imgpath in ImgPaths)
            {
                var test = Path.GetFileName(imgpath);
                var image = builder.LinkedResources.Add(imgpath);
                image.ContentId = MimeUtils.GenerateMessageId();
                image.ContentDisposition = new ContentDisposition() { Disposition = ContentDisposition.Inline };
                //HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
                HtmlFormat = HtmlFormat.Replace($"images/{test}", string.Format("cid:{0}", image.ContentId)); //use images/filename
            }
html asp.net core mailkit
1个回答
1
投票
这看起来像是问题:

<img src="images/cid:TPSXHQUDSAU4.JJRKUIEGLTZ5@Loralei" .../>

必须是:

<img src="cid:TPSXHQUDSAU4.JJRKUIEGLTZ5@Loralei" .../>

我的

猜测是为了解决此问题,您需要更改以下代码行:

HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
对此:

HtmlFormat = HtmlFormat.Replace(imgpath, string.Format("cid:{0}", image.ContentId));

希望有帮助!
© www.soinside.com 2019 - 2024. All rights reserved.