如何使用IMAP从C#中的gmail下载附件? [英] How to download attachment from gmail in C# using IMAP?

查看:163
本文介绍了如何使用IMAP从C#中的gmail下载附件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用控制台应用程序通过IMAP Service从邮件中下载文档.我在IMAP应用程序中使用"S22.Imap"程序集.我收到的所有邮件都包含IEnumerable中的附件.我如何下载这些文件?

I have using a console app for downloading document from the mail using IMAP Service. I use "S22.Imap" assembly in application for the IMAP. I got the all mails contains attached files in IEnumerable. How could I download these Files?

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

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

I would appreciate it, if you give a solution

推荐答案

附件类型上有一个名为ContentStream的属性,您可以在msdn文档中看到此属性:

The attachments type has a property on it called ContentStream you can see this on the msdn documentation: https://msdn.microsoft.com/en-us/library/system.net.mail.attachment(v=vs.110).aspx.

您可以使用类似的方法来保存文件:

Using that you can use something like this to then save the file:

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

因此,在GetMessages完成后,您可以执行以下操作:

So after GetMessages is done you could do:

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

这篇关于如何使用IMAP从C#中的gmail下载附件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆