如何使用IMAP在C#中从gmail下载附件?

San*_*v S 3 .net c# imap

我使用控制台应用程序使用IMAP服务从邮件下载文档.我在IMAP的应用程序中使用"S22.Imap"程序集.我得到的所有邮件都包含IEnumerable中的附件.我怎么能下载这些文件?

using (ImapClient client = new ImapClient(hostname, 993, username, password, AuthMethod.Login, true))
        {
            IEnumerable<uint> uids = client.Search(SearchCondition.Subject("Attachments"));
            IEnumerable<MailMessage> messages = client.GetMessages(uids,
                (Bodypart part) =>
                {
                    if (part.Disposition.Type == ContentDispositionType.Attachment)
                    {
                        if (part.Type == ContentType.Application &&
                           part.Subtype == "VND.MS-EXCEL")
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    return true;
                }
            );
       }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果你给出一个解决方案,我将不胜感激

Mar*_*rry 7

附件类型上有一个属性叫做ContentStream你可以在msdn文档上看到这个:https://msdn.microsoft.com/en-us/library/system.net.mail.attachment(v = vs.110).aspx .

使用它你可以使用这样的东西然后保存文件:

using (var fileStream = File.Create("C:\\Folder"))
{
    part.ContentStream.Seek(0, SeekOrigin.Begin);
    part.ContentStream.CopyTo(fileStream);
}
Run Code Online (Sandbox Code Playgroud)

编辑:所以GetMessages完成后你可以这样做:

foreach(var msg in messages)
{
    foreach (var attachment in msg.Attachments)
    {
        using (var fileStream = File.Create("C:\\Folder"))
        {
            attachment.ContentStream.Seek(0, SeekOrigin.Begin);
            attachment.ContentStream.CopyTo(fileStream);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)