从公共文件夹获取电子邮件c#

时间:2016-03-24 17:43:10

标签: c# email imap

我想从公共文件夹中获取邮件!我有以下代码,但只是从我的收件箱收到电子邮件!

Imap4Client imap = new Imap4Client();
imap.Connect("servername");
imap.LoginFast("username", "password");

var inbox = imap.SelectMailbox("Inbox");

1 个答案:

答案 0 :(得分:0)

我不知道您使用的是哪个IMAP库,但如果您使用MailKit,则可以轻松访问所需的任何文件夹(无论是在个人,共享还是其他名称空间中)。

using System;

using MailKit.Net.Imap;
using MailKit.Search;
using MailKit;
using MimeKit;

namespace TestClient {
    class Program
    {
        public static void Main (string[] args)
        {
            using (var client = new ImapClient ()) {
                client.Connect ("imap.gmail.com", 993, true);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove ("XOAUTH2");

                client.Authenticate (username, password);

                // Get a reference to the personal namespace as a folder:
                var personal = client.GetFolder (client.PersonalNamespaces[0]);

                // Get a list of subfolders within our personal namespace:
                foreach (var folder in personal.GetSubfolders ()) {
                    Console.WriteLine ("Name: {0}", folder.Name);

                    // To get the message count, we either need to Open()
                    // the folder or we can call Status() to just get
                    // the properties that we care about:
                    folder.Status (StatusItems.Count | StatusItems.Unread);

                    Console.WriteLine ("Count: {0}", folder.Count);
                    Console.WriteLine ("Unread: {0}", folder.Unread);

                    // If we want to fetch any of the messages (or get any
                    // message metadata, we'll need to actually Open() the
                    // folder:
                    folder.Open (FolderAccess.ReadWrite);

                    for (int i = 0; i < folder.Count; i++) {
                        var message = folder.GetMessage (i);
                        Console.WriteLine ("Subject: {0}", message.Subject);
                    }

                    // Of course, there are many other things we can do
                    // such as searching, getting meta info about the
                    // messages (such as flags, pre-parsed envelope headers
                    // the size, etc), setting flags, getting individual
                    // parts of the message, etc.

                    // Note: we can also get subfolders of this folder...
                    foreach (var subfolder in folder.GetSubfolders ()) {
                        // ...
                    }
                }

                client.Disconnect (true);
            }
        }
    }
}