上記のとおり、コンテンツIDを使用して、メールのHTML本文内の画像タグに添付ファイルをリンクします。以下は、MHTファイルを開き、リンクを調整し、結果を電子メールで送る完全なプログラムです。
Word Automation Serviceを使用して受信メールをMHTファイルに変換して電子メールで送信するクライアントがあります。問題は、Outlookが生のMHTをあまり気にせず、画像をインライン化しなかったことです。ここに私のPOCがあります。私はMailKit内の依存関係をカバーするBouncy Castle C#API(http://www.bouncycastle.org/csharp/)とテスト用のSMTPトラフィックを受信するためにローカルサーバー上で動作するAntix SMTP Server for Developers(http://antix.co.uk/Projects/SMTP-Server-For-Developers)をMimeKitとMailKit devのコード。以下は、既存の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", "[email protected]"));
messageMimeKit.To.Add(new MailboxAddress("to address", "[email protected]"));
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];
}
}
}
私は問題が何であるかを理解した後、Word文書をmhtmlに変換し、リンクを修正し、電子メールで送信するために何かを書いた。 – runrig