web-dev-qa-db-ja.com

MailMessageに添付のbase64画像を追加し、html本文で読み取ります

現在、MailMessageSmtpClientを使ってメールを送信する必要がありますが、string内のbase64MailAddressにある画像を送信する必要があります体。

Attachmentに配置する必要があることを理解しましたが、MailMessageクラスにbase64を配置し、画像を視覚化するために読み取る方法がわかりませんメールの本文。 URL画像パスがありません。

8
gvivetapl

画像をメールメッセージに埋め込むには:(これはnotメッセージに添付ファイルを追加するのと同じです)

メールの送信に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"/>
7

本文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をStreamに変換します。

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

MailMessageを設定します。

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);
4
nmDat
<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);
4
Akshey Bhat