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

5

我正在使用一个控制台应用程序通过IMAP服务从邮件中下载文件。在应用程序中,我使用“S22.Imap”程序集进行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;
                }
            );
       }

这里输入图片描述

如果您能提供解决方案,我将不胜感激。


1
在截图中,展开Base,然后你会得到ContentStream - Martheen
5个回答

9
附件类型有一个属性叫做ContentStream,你可以在MSDN文档中看到:https://msdn.microsoft.com/zh-cn/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);
}

编辑: 当 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);
        }
    }
}

1

确实是这样。楼主应该查看像这个的例子。 - Panagiotis Kanavos

0

这段代码将附件文件存储在C驱动器的下载文件夹中。

 foreach (var msg in messages)

                        {
                             foreach (var attachment in msg.Attachments)
                            {

                                byte[] allBytes = new byte[attachment.ContentStream.Length];
                                int bytesRead = attachment.ContentStream.Read(allBytes, 0, (int)attachment.ContentStream.Length);

                                string destinationFile = @"C:\Download\" + attachment.Name;

                                BinaryWriter writer = new BinaryWriter(new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None));
                                writer.Write(allBytes);
                                writer.Close();
                            }

                }

希望能对某人有所帮助


0

OP正在询问如何使用IMAP和特定的库。您发布的链接是关于POP的。 - Panagiotis Kanavos

0
messages.Attachments.Download();
messages.Attachments.Save("location", fileSaveName)

这样你就可以使用IMAP下载电子邮件附件


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接