我正在寻找从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无法解析命令
答案 0 :(得分:0)
此问题目前是AE.Net.Mail的一个漏洞。
请参阅以下网址以获取相关信息:
https://github.com/andyedinborough/aenetmail/issues/197
从错误信息和评论看起来,它与搜索条件中的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);
答案 1 :(得分:0)
@Ahmado你可以用pop3来阅读收件箱邮件。这不仅适用于gmail,也可以用于其他电子邮件。因此,您需要2个dll。使用nuget在您的应用程序中下载。 OpenPop.NET 和 AE.Net.Mail
第1步:根据您的凭据阅读所有收件箱电子邮件:
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,使用此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