在 C# 中使用 Pop3 读取电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading Email using Pop3 in C#
提问by Eldila
I am looking for a method of reading emails using Pop3 in C# 2.0. Currently, I am using code found in CodeProject. However, this solution is less than ideal. The biggest problem is that it doesn't support emails written in unicode.
我正在寻找一种在 C# 2.0 中使用 Pop3 阅读电子邮件的方法。目前,我正在使用CodeProject中的代码。然而,这种解决方案并不理想。最大的问题是它不支持用 unicode 编写的电子邮件。
采纳答案by VanOrman
I've successfully used OpenPop.NETto access emails via POP3.
我已经成功地使用OpenPop.NET通过 POP3 访问电子邮件。
回答by Martin Vobr
downloading the email via the POP3 protocol is the easy part of the task. The protocol is quite simple and the only hard part could be advanced authentication methods if you don't want to send a clear text password over the network (and cannot use the SSL encrypted communication channel). See RFC 1939: Post Office Protocol - Version 3 and RFC 1734: POP3 AUTHentication commandfor details.
通过 POP3 协议下载电子邮件是任务的简单部分。该协议非常简单,如果您不想通过网络发送明文密码(并且不能使用 SSL 加密通信通道),那么唯一困难的部分可能是高级身份验证方法。有关详细信息,请参阅RFC 1939:邮局协议 - 版本 3 和RFC 1734:POP3 AUTHentication 命令。
The hard part comes when you have to parse the received email, which means parsing MIME format in most cases. You can write quick&dirty MIME parser in a few hours or days and it will handle 95+% of all incoming messages. Improving the parser so it can parse almost any email means:
当您必须解析收到的电子邮件时,困难的部分就来了,这意味着在大多数情况下解析 MIME 格式。您可以在几小时或几天内编写快速而肮脏的 MIME 解析器,它将处理 95+% 的所有传入消息。改进解析器使其几乎可以解析任何电子邮件意味着:
- getting email samples sent from the most popular mail clients and improve the parser in order to fix errors and RFC misinterpretations generated by them.
- Making sure that messages violating RFC for message headers and content will not crash your parser and that you will be able to read every readable or guessable value from the mangled email
- correct handling of internationalization issues (e.g. languages written from righ to left, correct encoding for specific language etc)
- UNICODE
- Attachments and hierarchical message item tree as seen in "Mime torture email sample"
- S/MIME (signed and encrypted emails).
- and so on
- 获取从最流行的邮件客户端发送的电子邮件样本并改进解析器以修复它们生成的错误和 RFC 误解。
- 确保违反 RFC 的邮件标题和内容的邮件不会使您的解析器崩溃,并且您将能够从损坏的电子邮件中读取每个可读或可猜测的值
- 正确处理国际化问题(例如从右到左编写的语言,特定语言的正确编码等)
- 统一编码
- 附件和分层消息项树,如“Mime 酷刑电子邮件示例”中所示
- S/MIME(签名和加密的电子邮件)。
- 等等
Debugging a robust MIME parser takes months of work. I know, because I was watching my friend writing one such parser for the component mentioned below and was writing a few unit tests for it too ;-)
调试一个强大的 MIME 解析器需要几个月的工作。我知道,因为我正在看着我的朋友为下面提到的组件编写一个这样的解析器,并且也在为它编写一些单元测试;-)
Back to the original question.
回到最初的问题。
Following code taken from our POP3 Tutorial pageand links would help you:
以下来自我们的 POP3 教程页面和链接的代码将对您有所帮助:
//
// create client, connect and log in
Pop3 client = new Pop3();
client.Connect("pop3.example.org");
client.Login("username", "password");
// get message list
Pop3MessageCollection list = client.GetMessageList();
if (list.Count == 0)
{
Console.WriteLine("There are no messages in the mailbox.");
}
else
{
// download the first message
MailMessage message = client.GetMailMessage(list[0].SequenceNumber);
...
}
client.Disconnect();
回答by stephenbayer
call me old fashion but why use a 3rd party library for a simple protocol. I've implemented POP3 readers in web based ASP.NET application with System.Net.Sockets.TCPClient and System.Net.Security.SslStream for the encryption and authentication. As far as protocols go, once you open up communication with the POP3 server, there are only a handful of commands that you have to deal with. It is a very easy protocol to work with.
叫我老时尚,但为什么要使用 3rd 方库来实现简单的协议。我已经在基于 Web 的 ASP.NET 应用程序中实现了 POP3 阅读器,使用 System.Net.Sockets.TCPClient 和 System.Net.Security.SslStream 进行加密和身份验证。就协议而言,一旦您打开与 POP3 服务器的通信,您只需处理少数命令。这是一个非常容易使用的协议。
回答by Corey Trager
My open source application BugTracker.NETincludes a POP3 client that can parse MIME. Both the POP3 code and the MIME code are from other authors, but you can see how it all fits together in my app.
我的开源应用程序BugTracker.NET包括一个可以解析 MIME 的 POP3 客户端。POP3 代码和 MIME 代码均来自其他作者,但您可以在我的应用程序中看到它们是如何组合在一起的。
For the MIME parsing, I use http://anmar.eu.org/projects/sharpmimetools/.
对于 MIME 解析,我使用http://anmar.eu.org/projects/sharpmimetools/。
See the file POP3Main.cs, POP3Client.cs, and insert_bug.aspx
请参阅文件 POP3Main.cs、POP3Client.cs 和 insert_bug.aspx
回答by Pawel Lesnikowski
You can also try Mail.dll mail component, it has SSL support, unicode, and multi-national email support:
您也可以尝试Mail.dll 邮件组件,它具有 SSL 支持、unicode 和多国电子邮件支持:
using(Pop3 pop3 = new Pop3())
{
pop3.Connect("mail.host.com"); // Connect to server and login
pop3.Login("user", "password");
foreach(string uid in pop3.GetAll())
{
IMail email = new MailBuilder()
.CreateFromEml(pop3.GetMessageByUID(uid));
Console.WriteLine( email.Subject );
}
pop3.Close(false);
}
You can download it here at https://www.limilabs.com/mail
你可以在https://www.limilabs.com/mail下载它
Please note that this is a commercial product I've created.
请注意,这是我创建的商业产品。
回答by Richard Beier
I wouldn't recommend OpenPOP. I just spent a few hours debugging an issue - OpenPOP's POPClient.GetMessage() was mysteriously returning null. I debugged this and found it was a string index bug - see the patch I submitted here: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778. It was difficult to find the cause since there are empty catch{} blocks that swallow exceptions.
我不会推荐 OpenPOP。我只花了几个小时调试一个问题 - OpenPOP 的 POPClient.GetMessage() 神秘地返回 null。我调试了这个并发现它是一个字符串索引错误 - 请参阅我在此处提交的补丁:http: //sourceforge.net/tracker/? func=detail&aid=2833334&group_id=92166&atid=599778 。由于存在吞下异常的空 catch{} 块,因此很难找到原因。
Also, the project is mostly dormant... the last release was in 2004.
此外,该项目大多处于休眠状态……最后一次发布是在 2004 年。
For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.
目前我们仍在使用 OpenPOP,但我会看看人们在这里推荐的其他一些项目。
回答by Higty
HigLabo.Mail is easy to use. Here is a sample usage:
HigLabo.Mail 易于使用。这是一个示例用法:
using (Pop3Client cl = new Pop3Client())
{
cl.UserName = "MyUserName";
cl.Password = "MyPassword";
cl.ServerName = "MyServer";
cl.AuthenticateMode = Pop3AuthenticateMode.Pop;
cl.Ssl = false;
cl.Authenticate();
///Get first mail of my mailbox
Pop3Message mg = cl.GetMessage(1);
String MyText = mg.BodyText;
///If the message have one attachment
Pop3Content ct = mg.Contents[0];
///you can save it to local disk
ct.DecodeData("your file path");
}
you can get it from https://github.com/higty/higlaboor Nuget [HigLabo]
你可以从https://github.com/higty/higlabo或 Nuget [HigLabo] 获取
回答by Higty
I just tried SMTPop and it worked.
我刚刚尝试过 SMTPop,它奏效了。
- I downloaded this.
- Added
smtpop.dll
reference to my C# .NET project
- 我下载了这个。
- 添加了
smtpop.dll
对我的 C# .NET 项目的引用
Wrote the following code:
写了以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmtPop;
namespace SMT_POP3 {
class Program {
static void Main(string[] args) {
SmtPop.POP3Client pop = new SmtPop.POP3Client();
pop.Open("<hostURL>", 110, "<username>", "<password>");
// Get message list from POP server
SmtPop.POPMessageId[] messages = pop.GetMailList();
if (messages != null) {
// Walk attachment list
foreach(SmtPop.POPMessageId id in messages) {
SmtPop.POPReader reader= pop.GetMailReader(id);
SmtPop.MimeMessage msg = new SmtPop.MimeMessage();
// Read message
msg.Read(reader);
if (msg.AddressFrom != null) {
String from= msg.AddressFrom[0].Name;
Console.WriteLine("from: " + from);
}
if (msg.Subject != null) {
String subject = msg.Subject;
Console.WriteLine("subject: "+ subject);
}
if (msg.Body != null) {
String body = msg.Body;
Console.WriteLine("body: " + body);
}
if (msg.Attachments != null && false) {
// Do something with first attachment
SmtPop.MimeAttachment attach = msg.Attachments[0];
if (attach.Filename == "data") {
// Read data from attachment
Byte[] b = Convert.FromBase64String(attach.Body);
System.IO.MemoryStream mem = new System.IO.MemoryStream(b, false);
//BinaryFormatter f = new BinaryFormatter();
// DataClass data= (DataClass)f.Deserialize(mem);
mem.Close();
}
// Delete message
// pop.Dele(id.Id);
}
}
}
pop.Quit();
}
}
}