用c#从Gmail中读取电子邮件
本文关键字:读取 电子邮件 Gmail | 更新日期: 2023-09-27 18:05:26
我正在尝试阅读来自Gmail的电子邮件。我试过了我能找到的所有API/开源项目,但没有一个能正常工作。
谁有一个工作代码的样本,将允许我验证和下载电子邮件从Gmail帐户?
最终工作版本如下:https://stackoverflow.com/a/19570553/550198
使用from: https://github.com/pmengal/MailSystem.NET
下面是我完整的代码示例:
电子邮件存储库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);
}
}
}
}
另一个例子,这次使用MailKit
public class MailRepository : IMailRepository
{
private readonly string mailServer, login, password;
private readonly int port;
private readonly bool ssl;
public MailRepository(string mailServer, int port, bool ssl, string login, string password)
{
this.mailServer = mailServer;
this.port = port;
this.ssl = ssl;
this.login = login;
this.password = password;
}
public IEnumerable<string> GetUnreadMails()
{
var messages = new List<string>();
using (var client = new ImapClient())
{
client.Connect(mailServer, port, ssl);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate(login, password);
// The Inbox folder is always available on all IMAP servers...
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadOnly);
var results = inbox.Search(SearchOptions.All, SearchQuery.Not(SearchQuery.Seen));
foreach (var uniqueId in results.UniqueIds)
{
var message = inbox.GetMessage(uniqueId);
messages.Add(message.HtmlBody);
//Mark message as read
//inbox.AddFlags(uniqueId, MessageFlags.Seen, true);
}
client.Disconnect(true);
}
return messages;
}
public IEnumerable<string> GetAllMails()
{
var messages = new List<string>();
using (var client = new ImapClient())
{
client.Connect(mailServer, port, ssl);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate(login, password);
// The Inbox folder is always available on all IMAP servers...
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadOnly);
var results = inbox.Search(SearchOptions.All, SearchQuery.NotSeen);
foreach (var uniqueId in results.UniqueIds)
{
var message = inbox.GetMessage(uniqueId);
messages.Add(message.HtmlBody);
//Mark message as read
//inbox.AddFlags(uniqueId, MessageFlags.Seen, true);
}
client.Disconnect(true);
}
return messages;
}
}
使用[Test]
public void GetAllEmails()
{
var mailRepository = new MailRepository("imap.gmail.com", 993, true, "YOUREMAILHERE@gmail.com", "YOURPASSWORDHERE");
var allEmails = mailRepository.GetAllMails();
foreach(var email in allEmails)
{
Console.WriteLine(email);
}
Assert.IsTrue(allEmails.ToList().Any());
}
你不需要任何额外的第三方库如果一个总结最近的20封邮件对你来说是足够的。你可以从Gmail提供的API中读取数据:https://mail.google.com/mail/feed/atom
XML格式的响应可由以下代码处理:
try {
const string emailAddress = "YourEmail";
// App Password, not password
// See: https://support.google.com/accounts/answer/185833?hl=en
const string appPassword = "YourAppPassword";
string response;
string title;
string summary;
XmlDocument xmlDocument = new XmlDocument();
HttpClient httpClient = new HttpClient();
// Logging in Gmail server to get data
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{emailAddress}:{appPassword}")));
// Reading data and converting to string
response = await httpClient.GetStringAsync(@"https://mail.google.com/mail/feed/atom");
// Remove XML namespace to simplify parsing/selecting nodes
response = response.Replace(@"<feed version=""0.3"" xmlns=""http://purl.org/atom/ns#"">", @"<feed>");
// Loading into an XML so we can get information easily
xmlDocument.LoadXml(response);
// Amount of emails
string nr = xmlDocument.SelectSingleNode(@"/feed/fullcount").InnerText;
// Reading the title and the summary for every email
foreach (XmlNode node in xmlDocument.SelectNodes(@"/feed/entry")) {
title = node.SelectSingleNode("title").InnerText;
summary = node.SelectSingleNode("summary").InnerText;
Console.WriteLine($"> {title}");
Console.WriteLine($"{summary}");
Console.WriteLine();
}
} catch (Exception ex) {
MessageBox.Show($"Error retrieving mails: {ex.Message}");
}
您尝试过完全支持MIME的POP3电子邮件客户端吗?
如果你没有,这对你来说是一个很好的例子。作为一种选择;
OpenPop。净
。. NET类库,用于与POP3服务器通信。容易使用,但要强大。包括一个健壮的MIME解析器100个测试用例。欲了解更多信息,请访问我们的项目主页。
Lumisoft
您也可以尝试Mail.dll IMAP客户端。
它支持所有Gmail IMAP协议扩展:
- 线程ID,
- 消息ID,
- 标签,
- 本地化文件夹名称,
- Google搜索语法
- OAuth身份验证。
请注意Mail.dll是我开发的商业产品