Gmail的问题-使用MailKit嵌入图像

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

我正在尝试使用MailKit发送带有嵌入式图像的电子邮件。它在MS Outlook上运行良好。但是,图像不会在Gmail中显示为嵌入式图像。我尝试附加“ data:image / png; base64”格式,但它也适用于Outlook,但不适用于Gmail。

任何帮助将不胜感激!

public string SendEmail (MyModel myModel)
{
    var message = new MimeMessage();
    var bodyBuilder = new BodyBuilder
    {
        HtmlBody = myModel.Body
    };
    GetAllImgTags(bodyBuilder);
    message.Body = bodyBuilder.ToMessageBody();
    // Send Email Here...
    return "OK"
}

    public string GetAllImgTags(BodyBuilder bodyBuilder)
    {
        HtmlDocument document = new HtmlDocument();

        document.LoadHtml(bodyBuilder.HtmlBody);

        var imgList = document.DocumentNode.Descendants("img").Where(x =>
        {
            string src = x.GetAttributeValue("src", null) ?? "";
            return !string.IsNullOrEmpty(src);
        }).ToList();

        foreach(var item in imgList)
        {
            string currentSrcValue = item.GetAttributeValue("src", null);
            var file = Path.Combine(_env.WebRootPath,"images", currentSrcValue);
            if (File.Exists(file))
            {                    
                byte[] imageData = System.IO.File.ReadAllBytes(file);
                string contentId = string.Format("{0}@{1}", Path.GetFileName(file), Guid.NewGuid().ToString());
                LinkedResource inline = new LinkedResource(new MemoryStream(imageData), Image.Jpeg)
                {
                    ContentId = contentId,
                    TransferEncoding = TransferEncoding.Base64,
                    ContentLink = new Uri("cid:" + contentId),

                };
                inline.ContentType.Name = contentId;
                inline.ContentType.MediaType = Image.Jpeg;
                bodyBuilder.LinkedResources.Add(contentId, new MemoryStream(imageData));

                item.SetAttributeValue("src", "cid:" + contentId);
                inline.Dispose();
            }
        }

        bodyBuilder.HtmlBody = document.DocumentNode.OuterHtml;
        string result = document.DocumentNode.OuterHtml;
        return result;
    }

enter image description here

c# asp.net-core gmail mailkit
1个回答
1
投票

首先,为什么要创建System.Net.Mail对象,然后仅以任何方式使用它们而不使用它们?

© www.soinside.com 2019 - 2024. All rights reserved.