2017-04-13 167 views
1

我装盘使用ImapClient阅读来自Gmail的邮件 :阅读电子邮件

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无法解析命令

回答

0

这个问题目前还是一个开放的bug与AE.Net.Mail。

请参阅以下网址的信息:

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

它看起来像,从错误信息,并评论说,这是在搜索条件与日期时间做。

替换当前的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); 
+0

谢谢@Luke – Ahmado

+0

AE.Net.Mail已经死了好几年了,在这一点上,你可能要考虑切换到我的[MailKit](https:/ /github.com/jstedfast/MailKit)库,而不是这些错误。 – jstedfast

0

@Ahmado您可以使用POP3读取收件箱中的电子邮件。这不仅适用于gmail,也可以用于其他电子邮件。为此,您需要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; 
     } 

第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