Created
April 14, 2022 09:03
-
-
Save dima-hx/4594d510d94e4b56256427c15ca005e9 to your computer and use it in GitHub Desktop.
Add Attachment base64 image in MailMessage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static AlternateView ContentToAlternateView(string content) | |
{ | |
Stream Base64ToImageStream(string base64String) | |
{ | |
byte[] imageBytes = Convert.FromBase64String(base64String); | |
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); | |
return ms; | |
} | |
var imgCount = 0; | |
List<LinkedResource> resourceCollection = new List<LinkedResource>(); | |
foreach (Match m in Regex.Matches(content, @"<img([\s\S]+?)src\s?=\s?['""](?<srcAttr>[^'""]+?)['""]([\s\S]+?)\/?>")) | |
{ | |
imgCount++; | |
var srcAttribute = m.Groups["srcAttr"].Value; | |
string type = Regex.Match(srcAttribute, ":(?<type>.*?);base64,").Groups["type"].Value; | |
string base64 = Regex.Match(srcAttribute, "base64,(?<base64>.*?)$").Groups["base64"].Value; | |
//ignore replacement when match normal <img> tag | |
if (String.IsNullOrEmpty(type) || String.IsNullOrEmpty(base64)) continue; | |
content = content.Replace(srcAttribute, "cid:" + imgCount); | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment