从收件箱 gmail 中读取电子邮件

Read emails from Inbox gmail

我正在尝试阅读来自 gmail 的邮件 使用 ImapClient :

using AE.Net.Mail;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Plus.v1;
using Google.Apis.Plus.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Web;

namespace Web.FrontOffice.Utils
{
    public class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/gmail-dotnet-quickstart.json


        public static void ReadMailFromGmail()
        {

            UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = "My_ClientId", ClientSecret = "My_ClientSecret" },
                new[] { "https://mail.google.com/","https://www.googleapis.com/auth/userinfo.email"}, "user", CancellationToken.None, new FileDataStore("Analytics.Auth.Store")).Result;


            // Create Gmail API service.
            PlusService service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "My App"});
            // Define parameters of request.          
            Person me = service.People.Get("me").Execute();
            Person.EmailsData myAccountEmail = me.Emails.Where(a => a.Type == "account").FirstOrDefault();
            // List labels.
            ImapClient ic = new ImapClient("imap.gmail.com", myAccountEmail.Value, credential.Token.AccessToken, AE.Net.Mail.AuthMethods.SaslOAuth, 993, true);       
            ic.SelectMailbox("INBOX");

            // MailMessage represents, well, a message in your mailbox           
            var uids = ic.Search(SearchCondition.SentSince(new DateTime(2017, 4, 13)));
            foreach (var uid in uids)
            {
                MailMessage message = ic.GetMessage(uid);

                Debug.WriteLine(message.Body+"   "+message.Subject+"   "+message.Date);
            }          
        }
    }
}

'System.Exception' 类型的异常发生在 AE.Net.Mail.dll 中,但未在用户代码中处理

附加信息:xm003 BAD 无法解析命令

此问题目前是 AE.Net.Mail 的一个未解决的错误。

请参阅以下URL了解信息:

https://github.com/andyedinborough/aenetmail/issues/197

从bug信息和评论来看,好像和搜索条件中的DateTime有关。

如果我没有正确阅读评论,将您当前的 SearchCondition 替换为以下内容可能会防止出现问题:

var condition = new SearchCondition
{
    Value = string.Format(@"X-GM-RAW ""AFTER:{0:yyyy-MM-dd}""", new DateTime(2017, 4, 13));
}

// Then pass your condition in to the search function
var uids = ic.Search(condition);

@Ahmado 您可以使用 pop3 阅读收件箱电子邮件。这不仅适用于 gmail,还可以用于其他电子邮件 also.for,您需要 2 个 dll。使用 nuget 在您的应用程序中下载它。 OpenPop.NETAE.Net.Mail

第一步:根据您的凭证阅读所有收件箱邮件:

private DashBoardMailBoxJob ReceiveMails()
        {
            DashBoardMailBoxJob model = new DashBoardMailBoxJob();
            model.Inbox = new List<MailMessege>();

            try
            {
                EmailConfiguration email = new EmailConfiguration ();
                email.POPServer = "imap.gmail.com";
                email.POPUsername = ""; // type your username credential
                email.POPpassword = ""; // type your username credential
                email.IncomingPort = "993";
                email.IsPOPssl = true;


                int success = 0;
                int fail = 0;
                ImapClient ic = new ImapClient(email.POPServer, email.POPUsername, email.POPpassword, AuthMethods.Login, Convert.ToInt32(email.IncomingPort), (bool)email.IsPOPssl);
                // Select a mailbox. Case-insensitive
                ic.SelectMailbox("INBOX");
                int i = 1;
                int msgcount = ic.GetMessageCount("INBOX");
                int end = msgcount - 1;
                int start = msgcount - 40;
                // Note that you must specify that headersonly = false
                // when using GetMesssages().
                MailMessage[] mm = ic.GetMessages(start, end, false);
                foreach (var item in mm)
                {
                    MailMessege obj = new MailMessege();
                    try
                    {

                        obj.UID = item.Uid;
                        obj.subject = item.Subject;
                        obj.sender = item.From.ToString();
                        obj.sendDate = item.Date;
                        if (item.Attachments == null) { }
                        else obj.Attachments = item.Attachments;

                        model.Inbox.Add(obj);
                        success++;
                    }
                    catch (Exception e)
                    {
                        DefaultLogger.Log.LogError(
                            "TestForm: Message fetching failed: " + e.Message + "\r\n" +
                            "Stack trace:\r\n" +
                            e.StackTrace);
                        fail++;
                    }
                    i++;

                }
                ic.Dispose();
                model.Inbox = model.Inbox.OrderByDescending(m => m.sendDate).ToList();
                model.mess = "Mail received!\nSuccesses: " + success + "\nFailed: " + fail + "\nMessage fetching done";

                if (fail > 0)
                {
                    model.mess = "Since some of the emails were not parsed correctly (exceptions were thrown)\r\n" +
                                    "please consider sending your log file to the developer for fixing.\r\n" +
                                    "If you are able to include any extra information, please do so.";
                }
            }

            catch (Exception e)
            {
                model.mess = "Error occurred retrieving mail. " + e.Message;
            }
            finally
            {

            }
            return model;
        }

第二步:每封邮件都有一个唯一的id,使用它你可以得到邮件的详细信息:

public ActionResult GetMessegeBody(string id)
        {
            JsonResult result = new JsonResult();

            EmailConfiguration email = new EmailConfiguration();
            email.POPServer = "imap.gmail.com";
            email.POPUsername = "";
            email.POPpassword = "";
            email.IncomingPort = "993";
            email.IsPOPssl = true;

            ImapClient ic = new ImapClient(email.POPServer, email.POPUsername, email.POPpassword, AuthMethods.Login, Convert.ToInt32(email.IncomingPort), (bool)email.IsPOPssl);
            // Select a mailbox. Case-insensitive
            ic.SelectMailbox("INBOX");

            int msgcount = ic.GetMessageCount("INBOX");
            MailMessage mm = ic.GetMessage(id, false);

            if (mm.Attachments.Count() > 0)
            {
                foreach (var att in mm.Attachments)
                {
                    string fName;
                    fName = att.Filename;
                }
            }
            StringBuilder builder = new StringBuilder();

            builder.Append(mm.Body);
            string sm = builder.ToString();

            CustomerEmailDetails model = new CustomerEmailDetails();
            model.UID = mm.Uid;
            model.subject = mm.Subject;
            model.sender = mm.From.ToString();
            model.sendDate = mm.Date;
            model.Body = sm;
            if (mm.Attachments == null) { }
            else model.Attachments = mm.Attachments;

            return View("CreateNewCustomer", model);
        }

此代码示例用于 ASP.NET MVC。 对于您的情况,您还可以查看 code sample