Program Tip

C #에서 Pop3를 사용하여 이메일 읽기

programtip 2020. 10. 19. 12:36
반응형

C #에서 Pop3를 사용하여 이메일 읽기


C # 2.0에서 Pop3를 사용하여 이메일을 읽는 방법을 찾고 있습니다. 현재 저는 CodeProject에있는 코드를 사용하고 있습니다 . 그러나이 솔루션은 이상적이지 않습니다. 가장 큰 문제는 유니 코드로 작성된 이메일을 지원하지 않는다는 것입니다.


OpenPop.NET사용 하여 POP3를 통해 이메일에 액세스했습니다.


POP3 프로토콜을 통해 이메일을 다운로드하는 것은 작업의 쉬운 부분입니다. 프로토콜은 매우 간단하며 네트워크를 통해 일반 텍스트 암호를 전송하지 않으려는 경우 (SSL 암호화 된 통신 채널을 사용할 수없는 경우) 유일한 어려운 부분은 고급 인증 방법 일 수 있습니다. 자세한 내용은 RFC 1939 : Post Office Protocol-버전 3RFC 1734 : POP3 AUTHentication 명령 을 참조하십시오.

어려운 부분은 수신 된 이메일을 구문 분석해야 할 때 발생하며, 이는 대부분의 경우 MIME 형식을 구문 분석하는 것을 의미합니다. 몇 시간 또는 며칠 내에 빠르고 더러운 MIME 파서를 작성할 수 있으며 모든 수신 메시지의 95 % 이상을 처리합니다. 거의 모든 이메일을 구문 분석 할 수 있도록 구문 분석기를 개선하는 것은 다음을 의미합니다.

  • 가장 인기있는 메일 클라이언트에서 보낸 이메일 샘플을 가져 와서 생성 된 오류 및 RFC 오해를 수정하기 위해 구문 분석기를 개선합니다.
  • 메시지 헤더 및 콘텐츠에 대한 RFC를 위반하는 메시지가 구문 분석기를 손상시키지 않고 망가진 이메일에서 읽을 수 있거나 추측 할 수있는 모든 값을 읽을 수 있는지 확인합니다.
  • 국제화 문제의 올바른 처리 (예 : 오른쪽에서 왼쪽으로 작성된 언어, 특정 언어에 대한 올바른 인코딩 등)
  • 유니 코드
  • "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();

내 오픈 소스 애플리케이션 BugTracker.NET 에는 MIME를 구문 분석 할 수있는 POP3 클라이언트가 포함되어 있습니다. POP3 코드와 MIME 코드는 모두 다른 작성자의 것이지만 내 앱에서이 모든 것이 어떻게 조화를 이루는 지 알 수 있습니다.

MIME 구문 분석을 위해 http://anmar.eu.org/projects/sharpmimetools/ 사용 합니다.

POP3Main.cs, POP3Client.cs 및 insert_bug.aspx 파일을 참조하십시오.


SSL 지원, 유니 코드 및 다국적 이메일 지원이 포함 된 Mail.dll 메일 구성 요소를 사용해 볼 수도 있습니다 .

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 에서 다운로드 할 수 있습니다.

이것은 제가 만든 상업용 제품입니다.


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.


나는 OpenPOP를 추천하지 않을 것입니다. 문제를 디버깅하는 데 몇 시간을 보냈습니다. OpenPOP의 POPClient.GetMessage ()가 신비하게 null을 반환했습니다. 나는 이것을 디버깅했고 그것이 문자열 인덱스 버그라는 것을 발견했습니다-내가 제출 한 패치를보십시오 : http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778 . 예외를 삼키는 빈 catch {} 블록이 있기 때문에 원인을 찾기가 어려웠습니다.

또한 프로젝트는 대부분 휴면 상태입니다. 마지막 릴리스는 2004 년이었습니다.

지금은 여전히 ​​OpenPOP를 사용하고 있지만 여기에서 사람들이 추천 한 다른 프로젝트를 살펴 보겠습니다.


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] 에서 얻을 수 있습니다 .


방금 SMTPop을 시도했는데 작동했습니다.

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

참고URL : https://stackoverflow.com/questions/44383/reading-email-using-pop3-in-c-sharp

반응형