簡體   English   中英

使用MailKit / MimeKit從電子郵件中刪除附件

[英]Strip attachments from emails using MailKit / MimeKit

我正在使用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();

如果有人可以幫忙解決這個問題,我會非常感激。

解決方案實施FYI:

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

您可以檢索作為附件的所有MimePart https://github.com/jstedfast/MimeKit/blob/master/MimeKit/MimeMessage.cs#L734 ,然后遍歷所有Multipart並調用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));
}

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]);

我創建了一個應用程序,它使用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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM