【发布时间】:2021-06-26 10:29:26
【问题描述】:
我想发送带有图片的邮件。我编写的代码工作正常,但由于某种我不知道的原因,它不适用于 Outlook 客户端。 我发送的测试邮件是(左:Thunderbird,右:Outlook):
我的代码应该做的是:它从RichTextBox 获取 RTF 并将其转换为 HTML。这会将嵌入在 HTML 中的图像保留为 base64 字符串。我一一提取所有base64编码的图像并将它们放入MemoryStream,LinkedResource接受。由于邮件客户端通常不接受嵌入图像,因此我将 HTML 中的嵌入图像替换为 content-id。然后我设置LinkedResource 的一些属性并将其添加到AlternateView。然后将此备用视图添加到System.Net.Mail.MailMessage 并发送邮件。
对应代码:
MemoryStream mem = null;
private readonly Regex embeddedImageRegex = new Regex("src=\"data:image/.*?\"");
public MyHTMLMailMessage()
: base()
{
this.SubjectEncoding = Encoding.UTF8;
this.BodyEncoding = Encoding.UTF8;
this.IsBodyHtml = true;
}
public bool Send()
{
// create HTML View with images
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(HTML, System.Text.Encoding.UTF8, MediaTypeNames.Text.Html);
ReplaceEmbeddedImagesWithCID(htmlView);
this.AlternateViews.Add(htmlView);
this.Body = HTML;
SmtpClient client = new SmtpClient(server, port);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = String.IsNullOrEmpty(username);
try
{
client.Send(this);
return true;
}
catch (SmtpException e)
{
return false;
}
finally
{
mem?.Close();
}
}
private void ReplaceEmbeddedImagesWithCID(AlternateView altView)
{
string extension;
int imageIndex = 0;
string contentID = $"image{imageIndex}";
// go through every base64 string, create a content id and LinkedResource for it
while (embeddedImageRegex.IsMatch(HTML))
{
extension = new Regex("image/.*?;").Match(HTML).Value
.Replace("image/", "")
.Replace(";", "");
string base64img = embeddedImageRegex.Match(HTML).Value
.Replace("src=\"", "")
.Replace("\"", "")
.Split(',')[1];
HTML = embeddedImageRegex.Replace(HTML, $"src=\"cid:image{imageIndex}\"", 1);
byte[] byBitmap = Convert.FromBase64String(base64img);
mem = new MemoryStream(byBitmap);
mem.Position = 0;
LinkedResource linkedImage = new LinkedResource(mem, $"image/{extension}");
linkedImage.ContentId = contentID;
altView.LinkedResources.Add(linkedImage);
altView = AlternateView.CreateAlternateViewFromString(HTML, null, MediaTypeNames.Text.Html);
imageIndex++;
}
}
所以我尝试了不同的解决方案,但都没有奏效。 到目前为止我的步骤:
-
我在
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\x.0\Outlook\Options\Mail或HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\x.0\Common中编辑了一些注册码 -
我将图像作为 base64 字符串保留在 HTML 中
-
添加了一些属性
linkedImage.TransferEncoding = TransferEncoding.Base64;
linkedImage.ContentType.Name = contentID;
linkedImage.ContentLink = new Uri($"cid:{contentID}");
this.Headers.Add("Content-ID", $"<image{imageIndex}>");
this.Headers.Add("X-Attachment-Id", $"image{imageIndex}");
altView.TransferEncoding = TransferEncoding.QuotedPrintable;
这些对我都不起作用,尽管它似乎对其他人有所帮助。我忽略了什么吗?
【问题讨论】:
标签: c# html image outlook mailmessage