前述のように、コンテンツ ID を使用して、添付ファイルをメールの HTML 本文内のイメージ タグにリンクします。以下は、MHT ファイルを開き、リンクを調整し、結果を電子メールで送信するための完全なプログラムです。
Word Automation Service を使用して受信メールを MHT ファイルに変換し、メールで送信しているクライアントがいます。問題は、Outlook が生の MHT をあまり気にせず、画像をインライン化しなかったことです。これがソリューションのPOCです。コードでMimeKit と MailKit ( http://www.mimekit.net/ ) を使用し、Bouncy Castle C# API ( http://www.bouncycastle.org/csharp/ ) を使用して MailKit 内の依存関係をカバーし、開発者向けの Antix SMTP サーバー ( http://antix.co.uk/Projects/SMTP-Server-For-Developers ) はローカル サーバーで実行され、dev でコードをテストするための SMTP トラフィックを受信します。以下は、既存の MHT ファイルを開き、画像を埋め込んで電子メールで送信する POC コードです。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using MimeKit;
using MailKit;
using MimeKit.Utils;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
MimeMessage messageMimeKit = MimeMessage.Load(@"c:\test.mht");
var images = messageMimeKit.BodyParts.Where(x => x.ContentLocation.LocalPath.EndsWith("png"));
var bodyString = messageMimeKit.HtmlBody;
var builder = new BodyBuilder();
foreach (var item in images)
{
item.ContentId = MimeUtils.GenerateMessageId();
bodyString = bodyString.Replace(GetImageName(item), "cid:" + item.ContentId.ToString());
builder.LinkedResources.Add(item);
}
builder.HtmlBody = bodyString;
messageMimeKit.Body = builder.ToMessageBody();
messageMimeKit.From.Add(new MailboxAddress("from address", "NoReply_SharePoint2013Dev@smithmier.com"));
messageMimeKit.To.Add(new MailboxAddress("to address", "larry@smithmier.com"));
messageMimeKit.Subject = "Another subject line";
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.Connect("localhost");
client.Send(messageMimeKit);
client.Disconnect(true);
}
}
private static string GetImageName(MimeEntity item)
{
return item.ContentLocation.Segments[item.ContentLocation.Segments.Count() - 2] +
item.ContentLocation.Segments[item.ContentLocation.Segments.Count() - 1];
}
}
}