您可以通过多种方式获取 gmail 收件箱。
OpenPop
如果您只想使用 POP,并且不介意使用外部库,这似乎是最好/最简单的方法。 OpenPop 允许您访问安全/不安全的电子邮件帐户并让您选择端口。请参阅this post 以开始使用。
OpenPop 是实现邮件的开源 C#.NET 代码包
获取和解析。在撰写本文时,它仅使用 Microsoft .NET
框架库来完成所需的工作。但是对于访问安全弹出
服务器,openPop 可以通过使用一些 SSL 库来扩展。
例如,通过 Pop 访问 Gmail:
POPClient poppy = new POPClient();
poppy.Connect("pop.gmail.com", 995, true);
poppy.Authenticate(username@gmail.com, "password");
int Count = poppy.GetMessageCount();
if (Count > 0)
{
for (int i = Count; i >= 1; i -= 1)
{
OpenPOP.MIMEParser.Message m = poppy.GetMessage(i, false);
//use the parsed mail in variable 'm'
}
}
TcpClient POP3:
要通过 Pop3 从任何提供商处检索电子邮件,您可以使用 TcpClient。对于 Gmail,它只是略有不同,因为 Gmail 使用 SSL 和端口 995 进行 POP。有一个例子here:
// create an instance of TcpClient
TcpClient tcpclient = new TcpClient();
// HOST NAME POP SERVER and gmail uses port number 995 for POP
tcpclient.Connect("pop.gmail.com", 995);
// This is Secure Stream // opened the connection between client and POP Server
System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream());
// authenticate as client
sslstream.AuthenticateAsClient("pop.gmail.com");
Gmail Atom 供稿:
第一种方法是使用GmailAtomFeed,它是C# .Net Gmail Tools 的一部分。该网站说:
GmailAtomFeed 类提供了一个简单的对象层,用于
以编程方式访问 gmails atom 提要。在短短几行
将从 gmail 中检索和解析提要的代码。在那之后
可以通过对象层访问条目
AtomFeedEntryCollection,以及对原始提要和提要的访问
XmlDocument 也可用。
这是你如何使用它的一个例子:
// Create the object and get the feed
RC.Gmail.GmailAtomFeed gmailFeed = new RC.Gmail.GmailAtomFeed("username", "password");
gmailFeed.GetFeed();
// Access the feeds XmlDocument
XmlDocument myXml = gmailFeed.FeedXml
// Access the raw feed as a string
string feedString = gmailFeed.RawFeed
// Access the feed through the object
string feedTitle = gmailFeed.Title;
string feedTagline = gmailFeed.Message;
DateTime feedModified = gmailFeed.Modified;
//Get the entries
for(int i = 0; i < gmailFeed.FeedEntries.Count; i++) {
entryAuthorName = gmailFeed.FeedEntries[i].FromName;
entryAuthorEmail = gmailFeed.FeedEntries[i].FromEmail;
entryTitle = gmailFeed.FeedEntries[i].Subject;
entrySummary = gmailFeed.FeedEntries[i].Summary;
entryIssuedDate = gmailFeed.FeedEntries[i].Received;
entryId = gmailFeed.FeedEntries[i].Id;
}
IMAP
如果您不限于 POP,另一种方法是使用 IMAP。使用 IMAP,您可以连接到 SSL 服务器并选择一个端口:
using (Imap imap = new Imap())
{
imap.ConnectSSL("imap.gmail.com", 993);
imap.Login("angel_y@company.com", "xyx***"); // MailID As Username and Password
imap.SelectInbox();
List<long> uids = imap.SearchFlag(Flag.Unseen);
foreach (long uid in uids)
{
string eml = imap.GetMessageByUID(uid);
IMail message = new MailBuilder()
.CreateFromEml(eml);
Console.WriteLine(message.Subject);
Console.WriteLine(message.TextDataString);
}
imap.Close(true);
}