在C#中从Gmail阅读电子邮件

Sea*_*y84 26 .net c# gmail imap

我正在尝试阅读Gmail中的电子邮件.我已经尝试了我能找到的每个API /开源项目,并且不能让它们中的任何一个工作.

有没有人有一个工作代码示例,可以让我从Gmail帐户验证和下载电子邮件?

最终工作版本发布如下:https://stackoverflow.com/a/19570553/550198

Sea*_*y84 34

使用以下库:https://github.com/pmengal/MailSystem.NET

这是我的完整代码示例:

电子邮件存储库

using System.Collections.Generic;
using System.Linq;
using ActiveUp.Net.Mail;

namespace GmailReadImapEmail
{
    public class MailRepository
    {
        private Imap4Client client;

        public MailRepository(string mailServer, int port, bool ssl, string login, string password)
        {
            if (ssl)
                Client.ConnectSsl(mailServer, port);
            else
                Client.Connect(mailServer, port);
            Client.Login(login, password);
        }

        public IEnumerable<Message> GetAllMails(string mailBox)
        {
            return GetMails(mailBox, "ALL").Cast<Message>();
        }

        public IEnumerable<Message> GetUnreadMails(string mailBox)
        {
            return GetMails(mailBox, "UNSEEN").Cast<Message>();
        }

        protected Imap4Client Client
        {
            get { return client ?? (client = new Imap4Client()); }
        }

        private MessageCollection GetMails(string mailBox, string searchPhrase)
        {
            Mailbox mails = Client.SelectMailbox(mailBox);
            MessageCollection messages = mails.SearchParse(searchPhrase);
            return messages;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

[TestMethod]
public void ReadImap()
{
    var mailRepository = new MailRepository(
                            "imap.gmail.com",
                            993,
                            true,
                            "yourEmailAddress@gmail.com",
                            "yourPassword"
                        );

    var emailList = mailRepository.GetAllMails("inbox");

    foreach (Message email in emailList)
    {
        Console.WriteLine("<p>{0}: {1}</p><p>{2}</p>", email.From, email.Subject, email.BodyHtml.Text);
        if (email.Attachments.Count > 0)
        {
            foreach (MimePart attachment in email.Attachments)
            {
                Console.WriteLine("<p>Attachment: {0} {1}</p>", attachment.ContentName, attachment.ContentType.MimeType);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另一个例子,这次使用MailKit

public class MailRepository : IMailRepository
{
    private readonly string mailServer, login, password;
    private readonly int port;
    private readonly bool ssl;

    public MailRepository(string mailServer, int port, bool ssl, string login, string password)
    {
        this.mailServer = mailServer;
        this.port = port;
        this.ssl = ssl;
        this.login = login;
        this.password = password;
    }

    public IEnumerable<string> GetUnreadMails()
    {
        var messages = new List<string>();

        using (var client = new ImapClient())
        {
            client.Connect(mailServer, port, ssl);

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

            client.Authenticate(login, password);

            // The Inbox folder is always available on all IMAP servers...
            var inbox = client.Inbox;
            inbox.Open(FolderAccess.ReadOnly);
            var results = inbox.Search(SearchOptions.All, SearchQuery.Not(SearchQuery.Seen));
            foreach (var uniqueId in results.UniqueIds)
            {
                var message = inbox.GetMessage(uniqueId);

                messages.Add(message.HtmlBody);

                //Mark message as read
                //inbox.AddFlags(uniqueId, MessageFlags.Seen, true);
            }

            client.Disconnect(true);
        }

        return messages;
    }

    public IEnumerable<string> GetAllMails()
    {
        var messages = new List<string>();

        using (var client = new ImapClient())
        {
            client.Connect(mailServer, port, ssl);

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

            client.Authenticate(login, password);

            // The Inbox folder is always available on all IMAP servers...
            var inbox = client.Inbox;
            inbox.Open(FolderAccess.ReadOnly);
            var results = inbox.Search(SearchOptions.All, SearchQuery.NotSeen);
            foreach (var uniqueId in results.UniqueIds)
            {
                var message = inbox.GetMessage(uniqueId);

                messages.Add(message.HtmlBody);

                //Mark message as read
                //inbox.AddFlags(uniqueId, MessageFlags.Seen, true);
            }

            client.Disconnect(true);
        }

        return messages;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

[Test]
public void GetAllEmails()
{
    var mailRepository = new MailRepository("imap.gmail.com", 993, true, "YOUREMAILHERE@gmail.com", "YOURPASSWORDHERE");
    var allEmails = mailRepository.GetAllMails();

    foreach(var email in allEmails)
    {
        Console.WriteLine(email);
    }

    Assert.IsTrue(allEmails.ToList().Any());
}
Run Code Online (Sandbox Code Playgroud)

  • 为了实现这一点,您需要使用您的Gmail帐户启用"安全性较低的应用程序",如果这是您的选项.我做到了,现在代码工作了.在此处阅读更多内容:https://www.google.com/settings/security/lesssecureapps (3认同)
  • 什么是 ?IMailRepository。Mailkit 没有该接口。 (2认同)
  • @Nulle 这是来自我的代码库。您可以根据自己的用例删除该接口。 (2认同)

E-R*_*die 17

没有需要任何额外的第三方库.您可以阅读Gmail在此处提供的API中的数据:https://mail.google.com/mail/feed/atom

XML格式的响应可以通过以下代码处理:

try {
   System.Net.WebClient objClient = new System.Net.WebClient();
   string response;
   string title;
   string summary;

   //Creating a new xml document
   XmlDocument doc = new XmlDocument();

   //Logging in Gmail server to get data
   objClient.Credentials = new System.Net.NetworkCredential("Email", "Password");
   //reading data and converting to string
   response = Encoding.UTF8.GetString(
              objClient.DownloadData(@"https://mail.google.com/mail/feed/atom"));

   response = response.Replace(
        @"<feed version=""0.3"" xmlns=""http://purl.org/atom/ns#"">", @"<feed>");

   //loading into an XML so we can get information easily
   doc.LoadXml(response);

   //nr of emails
   nr = doc.SelectSingleNode(@"/feed/fullcount").InnerText;

   //Reading the title and the summary for every email
   foreach (XmlNode node in doc.SelectNodes(@"/feed/entry")) {
      title = node.SelectSingleNode("title").InnerText;
      summary = node.SelectSingleNode("summary").InnerText;
   }
} catch (Exception exe) {
   MessageBox.Show("Check your network connection");
}
Run Code Online (Sandbox Code Playgroud)

  • 这种方法的唯一问题对许多人来说很重要,那就是您无法通过ATOM路由获取消息正文的全文。 (2认同)
  • 爱您的答案-这些天,是否每件事都需要NuGet软件包才能使之可行。那就是我们变成的:( (2认同)

Son*_*nül 5

您是否尝试过具有完整MIME支持的 POP3 电子邮件客户端

如果你不这样做,那对你来说就是一个很好的例子.作为一个替代者;

OpenPop.NET

C#中的.NET类库,用于与POP3服务器通信.易于使用但功能强大.包含由数百个测试用例支持的强大的MIME解析器.有关更多信息,请访问我们的项目主页.

Lumisoft

  • POP没有获取文件夹. (4认同)