【问题标题】:Prevent LinkedResource image getting added as attachment防止 LinkedResource 图像被添加为附件
【发布时间】:2018-10-02 02:50:23
【问题描述】:

在使用 System.Net.Mail 发送电子邮件的页面上,我可以将图像嵌入到 html 格式的电子邮件中。

string logoPath = "W:\\WebSites\\logo.jpg";
            LinkedResource imagelink = new LinkedResource(logoPath, "image/jpg");
            imagelink.ContentId = "imageId";
            imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(MessageHeader + Message.ToString() + MessageFooter, null, "text/html");
            htmlView.LinkedResources.Add(imagelink);

在创建电子邮件的代码中,图像是这样嵌入的。

MessageHeader += "<img alt=\"Company Logo\" hspace=0 src=\"cid:imageId\" align=baseline border=0>";

这一切正常。徽标出现在 html 格式的电子邮件中应该出现的位置。但是,当用户收到电子邮件时,还会附上一张图片 - 在 Outlook 中,您会看到一个始终名为 ATT00001 的附件 - 如果您下载,它就是徽标图片。

如何防止徽标被添加为附件以及被嵌入?消息中带有徽标但还附加等待下载看起来不专业。用户抱怨他们认为有附件 - 但实际上它只是徽标。

【问题讨论】:

  • 我一直都明白这一点。我一直认为这是因为我设置了默认不显示图像的设置,但必须以某种方式包含它们。不过不确定。你得到了图像和属性?
  • 是的,我两者都有。该图像正确嵌入到我的 html 电子邮件中,但在电子邮件客户端中查看时它也显示为附件。我只是尝试将图像从 jpg 更改为 png 并没有附加。技术不好吗!
  • 您找到解决方案了吗?我的代码过去可以正常工作,但由于某种原因,一段时间后它开始执行您描述的相同操作。

标签: asp.net email embedded-resource


【解决方案1】:

我想出了这个问题的解决方案。添加 LinkedResource 对象时,您必须定义正确的 MIME 类型,如果这样做,电子邮件客户端将不会提供嵌入的图像作为附件。

这是从我的场景中抓取的示例代码(vb.net 代码):

    'Your email
    Dim _htmlSource As New StringBuilder("<html> ... YOUR HTML EMAIL ... </html>")
    Dim _linkedResources As New List(Of LinkedResource)
    Dim _href As String = "http://your.image.url/image.png"


    'Adding images
    Dim _imageStream As MemoryStream
    Dim _mimeType As String
    Using _wc = New WebClient
        _imageStream = New MemoryStream(_wc.DownloadData(_href))
        _mimeType = _wc.ResponseHeaders("content-type")
    End Using
    Dim _contentId As String = Guid.NewGuid.ToString

    _htmlSource.Replace(_href, "cid:" & _contentId)
    _linkedResources.Add(New LinkedResource(_imageStream, New ContentType(_mimeType)) With {.ContentId = _contentId})



    'Compile mail message
    Dim mail As New MailMessage
    mail.IsBodyHtml = True
    Dim _htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(_htmlSource.ToString(), Nothing, MediaTypeNames.Text.Html)
    _htmlView.TransferEncoding = TransferEncoding.EightBit
    _linkedResources.ForEach(Sub(lr) _htmlView.LinkedResources.Add(lr))

【讨论】:

    猜你喜欢
    • 2020-11-16
    • 1970-01-01
    • 2018-09-24
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多