在MailMessage中添加附件Base64图像并在html正文中读取它并在、文中、附件、图像

2023-09-03 14:51:43 作者:不努力,未来永远是个梦

目前,我必须使用MailMessageSmtpClient发送电子邮件,但我需要发送的图片当前位于base64string正文中。

我知道有必要把它放在Attachment中,但我不知道如何将base64放在MailMessage类中,然后阅读它,以便在电子邮件正文中可视化图像。我没有URL图像路径。

推荐答案

在邮件中嵌入图像:(与向邮件中添加附件不同)

163邮箱电脑端从手机上传图片作为附件

如果您使用的是system.net.mail命名空间来发送邮件,则不需要将图像转换为Base64。

var mail = new MailMessage();
var imageToInline = new LinkedResource("Your image full path", MediaTypeNames.Image.Jpeg);
            imageToInline.ContentId = "MyImage";
            alternateView.LinkedResources.Add(imageToInline);
mail.AlternateViews.Add(body);

更新:

这是将图像嵌入到邮件中的一种有点老套的方式。

Byte[] bitmapData = Convert.FromBase64String(FixBase64ForImage("Your base64 image string"));
System.IO.MemoryStream streamBitmap = new System.IO.MemoryStream(bitmapData);

public static string FixBase64ForImage(string Image)
{
        System.Text.StringBuilder sbText = new System.Text.StringBuilder(Image, Image.Length);
        sbText.Replace("
", string.Empty); sbText.Replace(" ", string.Empty);
        return sbText.ToString();
}


var mail = new MailMessage();
var imageToInline = new LinkedResource(streamBitmap , MediaTypeNames.Image.Jpeg);
imageToInline.ContentId = "MyImage";
alternateView.LinkedResources.Add(imageToInline);
mail.AlternateViews.Add(body);

并且您的html邮件正文应具有以下标记:

 <img alt ="" src ="cid:MyImage"/>