【问题标题】:Read emails from Inbox gmail阅读收件箱 gmail 中的电子邮件
【发布时间】:2017-04-13 13:16:58
【问题描述】:

我正在准备阅读来自 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);
            }          
        }
    }
}

在 AE.Net.Mail.dll 中出现“System.Exception”类型的异常,但未在用户代码中处理

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

【问题讨论】:

    标签: asp.net-mvc email google-api gmail imap


    【解决方案1】:

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

    有关信息,请参阅以下 URL:

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

    从bug信息和cmet看来,它与搜索条件中的DateTime有关。

    如果我正确读取 cmets,将您当前的 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);
    

    【讨论】:

    • AE.Net.Mail 在这一点上已经是一个死项目好几年了,你可能要考虑切换到我的 MailKit 库,而不是没有这些错误。
    【解决方案2】:

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

    Step1:根据您的凭据阅读所有收件箱电子邮件:

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

    第 2 步:每封电子邮件都有一个唯一的 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

    【讨论】:

      猜你喜欢
      • 2011-06-01
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 2011-10-11
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      相关资源
      最近更新 更多