如何在 C# API 中将图像或标志添加到电子邮件正文中?

8 浏览
0 Comments

如何在 C# API 中将图像或标志添加到电子邮件正文中?

我在通过电子邮件将图像作为内嵌图像发送时遇到了问题。

图像文件显示为附件,这是可以的,但内联图像部分只显示为红色的x。

以下是我目前的代码:

LinkedResource inline = new LinkedResource(filePath);
inline.ContentId = Guid.NewGuid().ToString();
MailMessage mail = new MailMessage();
Attachment att = new Attachment(filePath);
att.ContentDisposition.Inline = true;
mail.From = from_email;
mail.To.Add(data.email);
mail.Subject = "客户端:" + data.client_id + "已向您发送了一张截图";
mail.Body = String.Format(
    "

客户端:" + data.client_id + "已向您发送了一张截图

" + @"", inline.ContentId); mail.IsBodyHtml = true; mail.Attachments.Add(att);

0
0 Comments

问题的原因是代码中存在一处错误,即在邮件的body部分使用了`att.ContentId`而不是`inline.ContentId`。

解决方法是使用下面的代码,并注意在向`MailMessage`添加`AlternateView`时,该视图将成为邮件的正文,不需要填充`Body`属性。

代码如下:

string htmlBody = "

Picture

"; AlternateView avHtml = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html); LinkedResource inline = new LinkedResource("filename.jpg", MediaTypeNames.Image.Jpeg); inline.ContentId = Guid.NewGuid().ToString(); avHtml.LinkedResources.Add(inline); MailMessage mail = new MailMessage(); mail.AlternateViews.Add(avHtml); Attachment att = new Attachment(filePath); att.ContentDisposition.Inline = true; mail.From = from_email; mail.To.Add(data.email); mail.Subject = "Client: " + data.client_id + " Has Sent You A Screenshot"; mail.Body = String.Format("

Client: " + data.client_id + " Has Sent You A Screenshot

" + @"", att.ContentId); mail.IsBodyHtml = true; mail.Attachments.Add(att);

注意:上述代码中的`filePath`和`from_email`变量需要根据实际情况进行替换。

0