在 C# 中使用 Pop3 读取电子邮件

发布于 2024-07-04 22:53:14 字数 1557 浏览 7 评论 0 原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

浸婚纱 2024-07-11 22:53:14

我已成功使用 OpenPop.NET 通过 POP3 访问电子邮件。

I've successfully used OpenPop.NET to access emails via POP3.

柏林苍穹下 2024-07-11 22:53:14

通过 POP3 协议下载电子邮件是该任务中最简单的部分。 该协议非常简单,如果您不想通过网络发送明文密码(并且无法使用 SSL 加密通信通道),唯一困难的部分可能是高级身份验证方法。 请参阅 RFC 1939:邮局协议 - 版本 3
RFC 1734:POP3 身份验证命令 了解详细信息。

当您必须解析收到的电子邮件时,困难的部分就来了,这意味着在大多数情况下解析 MIME 格式。 您可以在几个小时或几天内编写快速且肮脏的 MIME 解析器,它将处理 95% 以上的传入消息。 改进解析器使其可以解析几乎所有电子邮件意味着:

  • 获取从最流行的邮件客户端发送的电子邮件样本并改进解析器以修复由它们生成的错误和 RFC 误解。
  • 确保消息头和内容违反 RFC 的消息不会使您的解析器崩溃,并且您将能够从损坏的电子邮件中读取每个可读或可猜测的值
  • 正确处理国际化问题(例如,从右到左书写的语言、正确编码特定语言等)
  • UNICODE
  • 附件和分层消息项树,如 " 中所示Mime 折磨电子邮件样本”
  • S/MIME(签名和加密的电子邮件)。
  • 等等

调试一个强大的 MIME 解析器需要花费数月的时间。 我知道,因为我正在看着我的朋友为下面提到的组件编写一个这样的解析器,并且也在为其编写一些单元测试;-)

回到原来的问题。

按照取自我们的 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();

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 command for details.

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:

  • 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

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 ;-)

Back to the original question.

Following code taken from our POP3 Tutorial page and links would help you:

// 
// 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();
那伤。 2024-07-11 22:53:14

可以说我是老派,但为什么要使用第三方库来实现简单的协议呢? 我已经在基于 Web 的 ASP.NET 应用程序中实现了 POP3 阅读器,并使用 System.Net.Sockets.TCPClient 和 System.Net.Security.SslStream 进行加密和身份验证。 就协议而言,一旦您打开与 POP3 服务器的通信,您只需处理少数命令。 这是一个非常容易使用的协议。

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.

萌无敌 2024-07-11 22:53:14

我的开源应用程序 BugTracker.NET 包含一个可以解析 MIME 的 POP3 客户端。 POP3 代码和 MIME 代码均来自其他作者,但您可以看到它们如何在我的应用程序中组合在一起。

对于 MIME 解析,我使用 http://anmar.eu.org/projects/sharpmimetools/

请参阅文件 POP3Main.cs、POP3Client.cs 和 insert_bug.aspx

My open source application BugTracker.NET includes 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.

For the MIME parsing, I use http://anmar.eu.org/projects/sharpmimetools/.

See the file POP3Main.cs, POP3Client.cs, and insert_bug.aspx

╰つ倒转 2024-07-11 22:53:14

我不推荐 OpenPOP。 我刚刚花了几个小时调试一个问题 - OpenPOP 的 POPClient.GetMessage() 神秘地返回 null。 我对此进行了调试,发现这是一个字符串索引错误 - 请参阅我在此处提交的补丁: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778。 很难找到原因,因为存在吞掉异常的空 catch{} 块。

另外,该项目大部分处于休眠状态......最后一个版本是在 2004 年。

目前我们仍在使用 OpenPOP,但我将看一下人们在这里推荐的其他一些项目。

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.

Also, the project is mostly dormant... the last release was in 2004.

For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.

○闲身 2024-07-11 22:53:14

您还可以尝试 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);      
}

您可以在 https://www.limilabs.com/mail 下载它

请注意这是我创建的商业产品。

You can also try Mail.dll mail component, it has SSL support, unicode, and multi-national email support:

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

Please note that this is a commercial product I've created.

逆蝶 2024-07-11 22:53:14

我刚刚尝试了 SMTPop,它成功了。

  1. 我下载了 这个
  2. 添加了对我的 C# .NET 项目的 smtpop.dll 引用

编写了以下代码:

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();
        }
    }
}

I just tried SMTPop and it worked.

  1. I downloaded this.
  2. Added smtpop.dll reference to my C# .NET project

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();
        }
    }
}
独留℉清风醉 2024-07-11 22:53:14

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"); 
} 

您可以从 https://github.com/higty/higlabo 获取它或 Nuget [HigLabo]

HigLabo.Mail is easy to use. Here is a sample usage:

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/higlabo or Nuget [HigLabo]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文