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

时间:2015-08-03 12:16:05

标签: c# .net 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;
                }
            );
       }

enter image description here

如果你提供解决方案,我将不胜感激

5 个答案:

答案 0 :(得分: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);
}

编辑: 所以在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 :(得分:1)

我认为最好的来源是文档http://smiley22.github.io/S22.Imap/Documentation/

答案 2 :(得分:0)

答案 3 :(得分:0)

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

这样您就可以使用IMAP在电子邮件中下载附件

答案 4 :(得分: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();
                            }

                }

希望帮助某人