Моя альтернатива:
Прежде всего, небольшое расширение:
public static class RegexExtensions
{
public static string GetPattern(this IEnumerable<string> valuesToSearch)
{
return string.Format("({0})", string.Join("|", valuesToSearch));
}
}
затем получите имена изображений из папки:
private string[] GetFullNamesOfImages()
{
string images = Path.Combine(_directoryName, "Images");
if (!Directory.Exists(images))
return new string[0];
return Directory.GetFiles(images);
}
затем заменить имена изображений на cid:
private string InsertImages(string body)
{
var images = GetFullNamesOfImages().Select(Path.GetFileName).ToArray();
return Regex.Replace(body, "(Images/)?" + images.GetPattern(), "cid:$2", RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
где body - это тело HTML, и, например, <img src="Images/logo_shadow.png" alt="" style="width: 100%;" />
будет заменено на <img src="cid:logo_shadow.png" alt="" style="width: 100%;" />
затем последнее действие: добавление самих изображений в почту:
private MailMessage CreateMail(SmtpClient smtp, string toAddress, string body)
{
var images = GetFullNamesOfImages();
string decodedBody = WebUtility.HtmlDecode(body);
var text = AlternateView.CreateAlternateViewFromString(decodedBody, null, MediaTypeNames.Text.Plain);
var html = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
foreach (var image in images)
{
html.LinkedResources.Add(new LinkedResource(image, new ContentType("image/png"))
{
ContentId = Path.GetFileName(image)
});
}
var credentials = (NetworkCredential) smtp.Credentials;
var message = new MailMessage(new MailAddress(credentials.UserName), new MailAddress(toAddress))
{
Subject = "Some subj",
Body = decodedBody
};
message.AlternateViews.Add(text);
message.AlternateViews.Add(html);
return message;
}