MailMessage に添付ファイルの base64 画像を追加し、html 本文で読み取る

本文の HTML を AlternateView に変換するメソッドが完成しました

bodyHtml の例 :

<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);

更新:

これは、mailMessage に画像を埋め込むややハックな方法です。

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 に im タグを使用します

または、以下のように添付できます

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