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

标签 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

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

最佳答案

附件类型有一个名为 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);
        }
    }
}

关于c# - 如何使用 IMAP 在 C# 中从 gmail 下载附件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31787037/

相关文章:

c# - 检查安装了哪个版本的 DirectX

c# - 为什么字符串指针位置不同?

c# - 静态只读字段的初始化顺序

c# - 从 C# 到 C++ 的回调函数

gmail - 如何使用 IMAP 协议(protocol)从 Gmail 的电子邮件中删除标签?

c# - 在 PHP 中通过 COM 访问 .NET 程序集

c# - 父节点内列表的序列化(集合扁平化)

.net - 使用 .NET Sockets C++/CLI 传输/接收位图

php - IMAP编码解码: UTF-8 issue

c++ - 使用 libcurl 和 C++ 将从 IMAP 服务器下载的电子邮件保存到文件中