在MailMessage中添加Attachment base64图像,并在html正文中读取

本文关键字:并在 html 正文 读取 base64 MailMessage 添加 Attachment 图像 | 更新日期: 2023-09-27 18:06:15

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

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

在MailMessage中添加Attachment base64图像,并在html正文中读取

将正文HTML转换为AlternateView 的完整方法

bodyHtml示例(您可以将其传递到下面的MailMessage代码块中(

<p>example</p>
<p><img src=' "data:image/jpeg;base64,---base64string---"></p>
<p>example</p>
<p><img src=' "data:image/png;base64,---base64string---"></p>
<p>something</p>

使用这种方法,您可以通过许多ESP(gmail、outlook…(可视化多个图像

private static AlternateView ContentToAlternateView(string content)
    {
        var imgCount = 0;
        List<LinkedResource> resourceCollection = new List<LinkedResource>();
        foreach (Match m in Regex.Matches(content, "<img(?<value>.*?)>"))
        {
            imgCount++;
            var imgContent = m.Groups["value"].Value;
            string type = Regex.Match(imgContent, ":(?<type>.*?);base64,").Groups["type"].Value;
            string base64 = Regex.Match(imgContent, "base64,(?<base64>.*?)'"").Groups["base64"].Value;
            if (String.IsNullOrEmpty(type) || String.IsNullOrEmpty(base64))
            {
                //ignore replacement when match normal <img> tag
                continue;
            }
            var replacement = " src='"cid:" + imgCount + "'"";
            content = content.Replace(imgContent, replacement);
            var tempResource = new LinkedResource(Base64ToImageStream(base64), new ContentType(type))
            {
                ContentId = imgCount.ToString()
            };
            resourceCollection.Add(tempResource);
        }
        AlternateView alternateView = AlternateView.CreateAlternateViewFromString(content, null, MediaTypeNames.Text.Html);
        foreach (var item in resourceCollection)
        {
            alternateView.LinkedResources.Add(item);
        }
        return alternateView;
    }

将Base64转换为流:

public static Stream Base64ToImageStream(string base64String)
    {
        byte[] imageBytes = Convert.FromBase64String(base64String);
        MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
        return ms;
    }

设置邮件信息:

MailMessage mail = new MailMessage();
mail.IsBodyHtml = true;                   
AlternateView alterView = ContentToAlternateView(bodyHtml);
mail.AlternateViews.Add(alterView);
//more settings
//...
//////////////
SmtpClient smtp = new SmtpClient(Host, Port) { EnableSsl = false };
smtp.Send(mail);

要将图像嵌入邮件中:(这与向邮件添加附件文件不同(

如果您使用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("'r'n", 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"/>
<body>
     <img src='data:image/jpeg;base64, <!-- base64 data --> />
   </body>

在邮件的HTML中使用img标记

或者你可以按照下面的连接

Attachment attachment = new Attachment(base64String);
attachment.TransferEncoding = TransferEncoding.Base64;
mailmessage.Attachments.Add(attachment);