如何使用c#中的pop3从gmail中检索邮件中的邮件正文?

这是代码:

protected void Button9_Click(object sender, EventArgs e) { try { // 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"); //bool flag = sslstream.IsAuthenticated; // check flag // Asssigned the writer to stream System.IO.StreamWriter sw = new StreamWriter(sslstream); // Assigned reader to stream System.IO.StreamReader reader = new StreamReader(sslstream); // refer POP rfc command, there very few around 6-9 command sw.WriteLine("USER your_gmail_user_name@gmail.com"); // sent to server sw.Flush(); sw.WriteLine("PASS your_gmail_password"); sw.Flush(); // RETR 1 will retrive your first email. it will read content of your first email sw.WriteLine("RETR 1"); sw.Flush(); // close the connection sw.WriteLine("Quit "); sw.Flush(); string str = string.Empty; string strTemp = string.Empty; while ((strTemp = reader.ReadLine()) != null) { // find the . character in line if (strTemp == ".") { break; } if (strTemp.IndexOf("-ERR") != -1) { break; } str += strTemp; } textbox1.text = str; textbox1.text += "
" + "Congratulation.. ....!!! You read your first gmail email "; } catch (Exception ex) { Response.Write(ex.Message); } }

消息体是一堆似乎是随机字符的东西。 我知道它不仅仅是一堆随机字符,而是一些需要解析和转换的代码。 如何阅读“邮件正文”中的内容?

我知道我不是直接回复你的答案,但阅读电子邮件是一项非常复杂的任务,我认为你可以通过外部库更好更快地实现这一目标,而不是自己实现。

有很多很好的实现,我通常使用OpenPop.NET,它工作正常,是开源。

https://sourceforge.net/projects/hpop/

你可以在互联网上找到很多例子,因为它非常受欢迎。

http://hpop.sourceforge.net/examples.php

你可以轻松获得所有邮件:

 using(Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect("pop.gmail.com", 995, true); // Authenticate ourselves towards the server client.Authenticate("username@gmail.com", "password", AuthenticationMethod.UsernameAndPassword); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // We want to download all messages List allMessages = new List(messageCount); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. // Most servers give the latest message the highest number for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); } } 

你可以得到完整的原始信息

 var mailbody = ASCIIEncoding.ASCII.GetString(message.RawMessage); 

或者如果是utf8编码的电子邮件:

 var encodedStringAsBytes = System.Convert.FromBase64String(message.RawMessage); var rawMessage =System.Text.Encoding.UTF8.GetString(encodedStringAsBytes); 

相反,如果您只想要邮件正文,则必须深入了解邮件结构:

http://hpop.sourceforge.net/documentation/OpenPop~OpenPop.Mime.MessagePart.html

我知道这不是一件容易的事,但正如我上面所述,电子邮件是复杂的对象。