5

我在网上查看了其他示例,但我无法弄清楚如何从 MimeMessage 对象下载和存储所有附件。我确实查看了 WriteTo(),但我无法让它工作。还想知道附件是否会按照原文件名保存,并在邮件中输入。这是我到目前为止所拥有的:

using (var client = new ImapClient())
{
    client.Connect(Constant.GoogleImapHost, Constant.ImapPort, SecureSocketOptions.SslOnConnect);
    client.AuthenticationMechanisms.Remove(Constant.GoogleOAuth);
    client.Authenticate(Constant.GoogleUserName, Constant.GenericPassword);

    if (client.IsConnected == true)
    {
        FolderAccess inboxAccess = client.Inbox.Open(FolderAccess.ReadWrite);
        IMailFolder inboxFolder = client.GetFolder(Constant.InboxFolder);
        IList<UniqueId> uids = client.Inbox.Search(SearchQuery.All);

        if (inboxFolder != null & inboxFolder.Unread > 0)
        {
            foreach (UniqueId msgId in uids)
            {
                MimeMessage message = inboxFolder.GetMessage(msgId);

                foreach (MimeEntity attachment in message.Attachments)
                {
                    //need to save all the attachments locally
                }
            }
        }
    }
}
4

1 回答 1

19

这在“如何保存附件?”的常见问题中都有解释。部分。

这是您在问题中发布的代码的固定版本:

using (var client = new ImapClient ()) {
    client.Connect (Constant.GoogleImapHost, Constant.ImapPort, SecureSocketOptions.SslOnConnect);
    client.AuthenticationMechanisms.Remove (Constant.GoogleOAuth);
    client.Authenticate (Constant.GoogleUserName, Constant.GenericPassword);

    client.Inbox.Open (FolderAccess.ReadWrite);
    IList<UniqueId> uids = client.Inbox.Search (SearchQuery.All);

    foreach (UniqueId uid in uids) {
        MimeMessage message = client.Inbox.GetMessage (uid);

        foreach (MimeEntity attachment in message.Attachments) {
            var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name;

            using (var stream = File.Create (fileName)) {
                if (attachment is MessagePart) {
                    var rfc822 = (MessagePart) attachment;

                    rfc822.Message.WriteTo (stream);
                } else {
                    var part = (MimePart) attachment;

                    part.Content.DecodeTo (stream);
                }
            }
        }
    }
}

几点注意事项:

  1. 验证后无需检查是否client.IsConnected。如果它没有连接,它会在方法中抛出异常Authenticate()Connect()如果它没有成功,它也会在方法中引发异常。IsConnected如果您实际上只是调用了 2 条线路,则无需检查状态Connect()
  2. 你为什么要检查inboxFolder.Unread你是否在任何地方都没有使用它?如果您只想下载未读邮件,请将您的搜索更改为SearchQuery.NotSeen只为您提供未读邮件 UID。
  3. 我删除了您的IMailFolder inboxFolder = client.GetFolder(Constant.InboxFolder);逻辑,因为您不需要它。如果您要使用 进行搜索client.Inbox,则不要使用不同的文件夹对象迭代结果。
于 2017-04-10T23:14:15.833 回答