6

我正在使用 MailKit 库来处理电子邮件,它运行良好。但是,我正在尝试将电子邮件拆分为其组成文件 a)主要电子邮件(无附件) b)单独的附件文件,以存储在文件系统上。

我可以单独保存附件,但似乎无法从电子邮件正文代码中删除它们。即他们得到与主要电子邮件一起被保存,因此复制数据。:/

我试过了:

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;
        }
4

3 回答 3

10

您可以检索所有MimePart作为附件的 s https://github.com/jstedfast/MimeKit/blob/master/MimeKit/MimeMessage.cs#L734然后遍历所有Multiparts 并调用https://github.com/jstedfast/ MimeKit/blob/master/MimeKit/Multipart.cs#L468用于删除附件。

下面的示例对邮件做了一些假设,例如只有一个Multipart电子邮件客户端(Outlook)非常有创意地制作邮件。

static void Main(string[] args)
{
    var mimeMessage = MimeMessage.Load(@"x:\sample.eml");
    var attachments = mimeMessage.Attachments.ToList();
    if (attachments.Any())
    {
        // Only multipart mails can have attachments
        var multipart = mimeMessage.Body as Multipart;
        if (multipart != null)
        {
            foreach(var attachment in attachments)
            {
                multipart.Remove(attachment);
            }
        }
        mimeMessage.Body = multipart;
    }
    mimeMessage.WriteTo(new FileStream(@"x:\stripped.eml", FileMode.CreateNew));
}
于 2014-06-11T19:48:03.230 回答
7

MimeKit 0.38.0.0 开始,您将能够使用MimeIterator遍历 MIME 树结构以收集您想要删除(并删除它们)的附件列表。为此,您的代码将如下所示:

var attachments = new List<MimePart> ();
var multiparts = new List<Multipart> ();
var iter = new MimeIterator (message);

// collect our list of attachments and their parent multiparts
while (iter.MoveNext ()) {
    var multipart = iter.Parent as Multipart;
    var part = iter.Current as MimePart;

    if (multipart != null && part != null && part.IsAttachment) {
        // keep track of each attachment's parent multipart
        multiparts.Add (multipart);
        attachments.Add (part);
    }
}

// now remove each attachment from its parent multipart...
for (int i = 0; i < attachments.Count; i++)
    multiparts[i].Remove (attachments[i]);
于 2014-06-14T23:15:35.723 回答
0

我创建了一个应用程序,它也使用 Mailkit 下载电子邮件和附件。我遇到了一个问题:从 iOS 发送的附有图片的电子邮件没有得到正确处理。MailKit 没有将图像添加到附件列表中。

我使用此方法仅获取消息的文本:

private static string GetPlainTextFromMessageBody(MimeMessage message)
    {
        //content type needs to match text/plain otherwise i would store html into DB
        var mimeParts = message.BodyParts.Where(bp => bp.IsAttachment == false && bp.ContentType.Matches("text", "plain"));
        foreach (var mimePart in mimeParts)
        {
            if (mimePart.GetType() == typeof(TextPart))
            {
                var textPart = (TextPart)mimePart;
                return textPart.Text;
            }
        }
        return String.Empty;
    }

这是我用来只下载 .jpg 文件的方法:

foreach (var attachment in message.BodyParts.Where(bp => !string.IsNullOrEmpty(bp.FileName)))
{
    if (attachment.FileName.ToLowerInvariant().EndsWith(".jpg"))
    {
        //do something with the image here
    }
}
于 2014-06-11T21:26:54.430 回答