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

2023-09-02 01:56:46 作者:紫衫龙王罩

我想读从Gmail电子邮件。我想尽API /开源项目,我能找到,并不能得到任何人的工作。

I am trying to read emails from Gmail. I have tried every API / open source project I can find, and can not get any of them working.

有没有人有工作code的样本,让我进行身份验证,并从Gmail帐户下载电子邮件?

Does anyone have a sample of working code that will allow me to authenticate and download emails from a Gmail account?

最后工作版本贴出如下: http://stackoverflow.com/a/19570553/550198

Final working version posted below: http://stackoverflow.com/a/19570553/550198

推荐答案

从使用库: HTTP://mailsystem.$c $ cplex.com /

下面是我的完整code样品:

电子邮件信息库

Here is my complete code sample:

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

用法

[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);
            }
        }
    }
}
 
精彩推荐