简体   繁体   English

我在使用IMAP阅读电子邮件时获取原始文本

[英]I am getting raw text while reading emails using IMAP

I have taken some code from MSDN to read emails using IMAP Client. 我从MSDN获取了一些代码来使用IMAP Client读取电子邮件。 I have changed little bit code so i can only read unseen email. 我更改了一点代码,所以我只能阅读看不见的电子邮件。 I am writing all response in Richtextbox. 我在Richtextbox中写了所有回复。

The problems is format of Body text of Email is unreadable while all other text is fine. 问题是电子邮件的正文文本的格式是不可读的,而所有其他文本都很好。

    void ReadEmail()
    {
        try
        {

            // there should be no gap between the imap command and the \r\n       
            // ssl.read() -- while ssl.readbyte!= eof does not work because there is no eof from server 
            // cannot check for \r\n because in case of larger response from server ex:read email message 
            // there are lot of lines so \r \n appears at the end of each line 
            //ssl.timeout sets the underlying tcp connections timeout if the read or write 
            //time out exceeds then the undelying connection is closed 
            tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);

            ssl = new System.Net.Security.SslStream(tcpc.GetStream());
            ssl.AuthenticateAsClient("imap.gmail.com");
            receiveResponse("");


            username = "charlie@gmail.com";
            password = "********";

            receiveResponse("$ LOGIN " + username + " " + password + "  \r\n");

            receiveResponse("$ LIST " + "\"\"" + " \"*\"" + "\r\n");

            receiveResponse("$ SELECT INBOX\r\n");
            receiveResponse("$ UID SEARCH UNSEEN\r\n");
           MatchCollection collection= Regex.Matches(Result,@" (\d{1,4})");
           foreach (Match m in collection)
           { 
           UNREAD_UID.Add(int.Parse(m.Groups[1].Value));
           }
            foreach (int x in UNREAD_UID)
            {

                     receiveResponse("$ FETCH " +x + " body[header]\r\n");
                    richTextBox1.Text += Environment.NewLine+"-----------------------------------------------------------------------------------------------------------------------"+Environment.NewLine;
                    receiveResponse("$ FETCH " +x + " body[text]\r\n");
                    richTextBox1.Text += Environment.NewLine + "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2" + Environment.NewLine;
                    richTextBox1.Update();
            }


            //receiveResponse("$ STATUS INBOX (MESSAGES)\r\n");


          //  int number = 1;



            receiveResponse("$ LOGOUT\r\n");
        }
        catch (Exception ex)
        {
            Console.WriteLine("error: " + ex.Message);
        }
        finally
        {
            if (sw != null)
            {
                sw.Close();
                sw.Dispose();
            }
            if (ssl != null)
            {
                ssl.Close();
                ssl.Dispose();
            }
            if (tcpc != null)
            {
                tcpc.Close();
            }
        }
     }

   void receiveResponse(string command)
    {
        try
        {
            if (command != "")
            {
                if (tcpc.Connected)
                {
                    dummy = Encoding.ASCII.GetBytes(command);
                    ssl.Write(dummy, 0, dummy.Length);
                }
                else
                {
                    throw new ApplicationException("TCP CONNECTION DISCONNECTED");
                }
            }
            ssl.Flush();
            buffer = new byte[5120];
            bytes = ssl.Read(buffer, 0, 5120);
            sb.Append(Encoding.ASCII.GetString(buffer));
            Result = sb.ToString();
            richTextBox1.Text += Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + sb.ToString();
            sb = new StringBuilder();

        }
        catch (Exception ex)
        {
            throw new ApplicationException(ex.Message);
        }
    } 

Here is Sample of what i am getting 这是我得到的样本

108 FETCH (BODY[TEXT] {25656} DQoNCg0KDQo8IURPQ1RZUEUgaHRtbD4NCjxodG1sPg0KPGhlYWQ+DQo8dGl0bGU+TWlj cm9zb2Z0IHR1cm5zIChhbG1vc3QpIGFueSBjYW1lcmEgaW50byBhIEtpbmVjdDwvdGl0 bGU+DQo8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRleHQv aHRtbDsgY2hhcnNldD1VVEYtOCI+DQo8bWV0YSBuYW1lPSJ2aWV3cG9ydCIgY29udGVu dD0id2lkdGg9ZGV2aWNlLXdpZHRoIj4NCjwhLS0gRWZmaW5nIFdpbmRvd3MgOCBNYWls IGNsaWVudC4gQWRkIC13ZWJraXQtbWluLWRldmljZS1waXhlbC1yYXRpbzogMSB0byBz Y2FyZSBpdCBhd2F5IGZyb20gdGhpcyBiaXQuIC0tPg0KPHN0eWxlIHR5cGU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pbi1kZXZpY2UtcGl4ZWwtcmF0aW86IDEpIHsNCgkuYm9keS1j b250YWluZXIgeyB3aWR0aDoxMDAlICFpbXBvcnRhbnQ7IH0NCgkuYmFubmVyICAgICAg ICAgeyBkaXNwbGF5OiBub25lICFpbXBvcnRhbnQ7IH0NCgkubW9iaWxlLWJhbm5lciAg eyBkaXNwbGF5OiBibG9jayAhaW1wb3J0YW50OyB3aWR0aDozNDBweCAhaW1wb3J0YW50 OyBiYWNrZ3JvdW5kOiB1cmwoaHR0cDovL3d3dy5jb2RlcHJvamVjdC5jb20vc2NyaXB0 L21haWxvdXRzL3RlbXBsYXRlcy9uZXdzbGV0dGVyLWluc2lkZXIucG5nKSBuby1yZXBl YXQg dG9wIGxlZ dG9wIGxlZ

Kindly help me. 请帮助我。

You need to examine the Content-Transfer-Encoding header to undo Transfer encoding (in this case, that's Base64. Other alternatives are 7-bit or Quoted Printable). 您需要检查Content-Transfer-Encoding标头以撤消传输编码(在这种情况下,它是Base64。其他替代方案是7位或Quoted Printable)。 Or, better, download the entire message (Body[]) and apply a MIME parser/decoder to it to get an object representation of the headers, body, and attachments. 或者,更好的是,下载整个消息(Body [])并对其应用MIME解析器/解码器以获取标题,正文和附件的对象表示。

Max's answer above is correct, but I'm going to illustrate how to implement his suggestion using my MailKit library: Max的答案是正确的,但我将说明如何使用我的MailKit库实现他的建议:

using (var client = new ImapClient ()) {
    client.Connect ("imap.gmail.com", 993, true);

    // since we're not using an OAuth2 token, remove it from the set
    // of possible authentication mechanisms to try:
    client.AuthenticationMechanisms.Remove ("XOAUTH2");

    client.Authenticate ("charlie@gmail.com", "*****");

    // SELECT the INBOX folder
    client.Inbox.Open (FolderAccess.ReadWrite);

    foreach (var uid in client.Inbox.Search (SearchQuery.NotSeen)) {
        var message = client.Inbox.GetMessage (uid);

        // at this point, 'message' is a MIME DOM that you can walk
        // over to get the particular MIME-part that you want. For
        // example, we could get a body part with a filename of
        // "test.txt" using LINQ like this:
        var attachment = message.BodyParts.OfType<MimePart> ()
            .FirstOrDefault (x => x.FileName == "test.txt");

        // decode the content to a MemoryStream:
        using (var memory = new MemoryStream ()) {
            attachment.ContentObject.DecodeTo (memory);
        }

        // since the attachment is probably a TextPart
        // (based on the file extension above), we can actually
        // use a simpler approach:
        var textPart = attachment as TextPart;
        if (textPart != null) {
            // decode the content and convert into a 'string'
            var text = textPart.Text;
        }
    }

    client.Disconnect (true);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从Gmail C#阅读电子邮件-IMAP - Reading Emails from Gmail C# - IMAP 我正在使用Koolwired.Imap通过iMAP检索附件。 - I am using Koolwired.Imap to retrieve attachments via iMAP. 使用IMAP计算Gmail中的电子邮件数量 - Count number of emails in gmail using IMAP Mailkit 使用 Imap 连接到 Hotmail 并获取电子邮件 - Mailkit using Imap to connect to Hotmail and fetch emails 使用iTextSharp从PDF文件提取文本时,出现此错误:“找不到图像数据或EI” - While extracting text from PDF file using iTextSharp, I am getting this error: “Could not find image data or EI” 使用iTextSharp从PDF文件提取文本时,出现此错误:“找不到图像数据或EI” - While extracting text from PDF file using iTextSharp, I am getting this error: “Could not find image data or EI” 在asp.net中使用会话时出现错误 - I am getting error while using sessions in asp.net 尝试使用HttpClient检索AccesToken时出现错误 - While trying to retrieve the AccesToken using HttpClient I am getting an error 为什么在使用for和while循环时会得到不同的结果? - Why am I getting different results when using for and while loops? 我在读取文件时做对了吗? - Am I doing it right while reading a file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM