【发布时间】:2014-08-01 23:29:13
【问题描述】:
我正在使用 MailKit 库来处理电子邮件,效果很好。但是,我正在尝试将电子邮件拆分为其组成文件 a) 主要电子邮件(无附件) b) 单独的附件文件,以存储在文件系统上。
我可以单独保存附件,但似乎无法从电子邮件正文代码中删除它们。 IE。它们与主电子邮件一起保存,因此重复数据。 :/
我试过了:
foreach (MimePart part in inMessage.BodyParts)
{
if (part.IsAttachment)
{
// Remove MimePart < This function isn't available on the collection.
}
}
也试过了:
var builder = new BodyBuilder();
foreach (MimePart part in inMessage.BodyParts)
{
if (!part.IsAttachment)
{
// Add MimeParts to collection < This function isn't available on the collection.
}
}
outMessage.Body = builder.ToMessageBody();
如果有人能提供帮助,我将不胜感激。
解决方案实施仅供参考:
private string GetMimeMessageOnly(string outDirPath)
{
MimeMessage message = (Master as fsEmail).GetMimeMessage();
if (message.Attachments.Any())
{
var multipart = message.Body as Multipart;
if (multipart != null)
{
while (message.Attachments.Count() > 0)
{
multipart.Remove(message.Attachments.ElementAt(0));
}
}
message.Body = multipart;
}
string filePath = outDirPath + Guid.NewGuid().ToString() + ".eml";
Directory.CreateDirectory(Path.GetDirectoryName(outDirPath));
using (var cancel = new System.Threading.CancellationTokenSource())
{
using (var stream = File.Create(filePath))
{
message.WriteTo(stream, cancel.Token);
}
}
return filePath;
}
并且只获取附件:
private List<string> GetAttachments(string outDirPath)
{
MimeMessage message = (Master as fsEmail).GetMimeMessage();
List<string> list = new List<string>();
foreach (MimePart attachment in message.Attachments)
{
using (var cancel = new System.Threading.CancellationTokenSource())
{
string filePath = outDirPath + Guid.NewGuid().ToString() + Path.GetExtension(attachment.FileName);
using (var stream = File.Create(filePath))
{
attachment.ContentObject.DecodeTo(stream, cancel.Token);
list.Add(filePath);
}
}
}
return list;
}
【问题讨论】:
-
谢谢,但是这个链接是基于 Mail.dll 的,我想最好还是使用 MailKit。
-
FWIW,除非您计划取消将附件保存到磁盘,否则您无需创建取消令牌。您可以使用 CancellationToken.None 或根本不传递取消令牌。