【问题标题】:how to save email body into text file in c#如何在c#中将电子邮件正文保存到文本文件中
【发布时间】:2017-05-01 12:10:56
【问题描述】:

我正在尝试将我的收件箱电子邮件复制到文本文件,然后在此文本文件中搜索 word。如果这个词存在,我将使用这个词从 db 中查询 email-id 最后将这封邮件转发到这个 email-id。 我的问题是我无法将电子邮件复制到文本文件中。 msg 变量始终为空 这是我的代码:

using (Pop3Client client = new Pop3Client())
{
    client.Connect("pop.gmail.com", 995, true);
    client.Authenticate("mymail@gmail.com", "pasword", AuthenticationMethod.UsernameAndPassword);

    // Get the number of messages in the inbox
    int messageCount = client.GetMessageCount();

    for (int i = messageCount; i > 0; i--)
    {
        string msg = client.GetMessage(i).MessagePart.GetBodyAsText().ToString();

        System.IO.File.WriteAllText(@"d:\\My File2.log", msg.ToString());
        var body = System.IO.File.ReadLines(@"d:\\My File2.log");
        if (body.Contains("cusotmer ID: X"))
        {
            getemailadress();
            sendemail();
        }
    }
}

【问题讨论】:

  • 您忘记提问了吗?
  • 您的代码在什么方面不起作用?描述问题。
  • 为什么要将消息正文写入文件,然后再次读取以搜索文本。只需从 msg 变量中读取它,然后将其保存为成功或失败。
  • @marwen1:您编辑了问题,但没有添加任何信息。请具体描述问题是什么。实际上是什么失败了?您是否遇到某种错误?意外的结果/行为?当您调试时,具体会发生什么以及您预期会发生什么?
  • @david :没有收到任何错误我的问题是文本文件总是空的。我的问题 hir :string msg = client.GetMessage(i).MessagePart.GetBodyAsText().ToString();

标签: c# asp.net .net asp.net-mvc-4


【解决方案1】:

你能用这段代码吗: var mailbody = ASCIIEncoding.ASCII.GetString(message.RawMessage); 像这样:

using (Pop3Client client = new Pop3Client())
{
    client.Connect("pop.gmail.com", 995, true);
    client.Authenticate("mymail@gmail.com", "pasword", AuthenticationMethod.UsernameAndPassword);

    // Get the number of messages in the inbox
    int messageCount = client.GetMessageCount();

    for (int i = messageCount; i > 0; i--)
    {

string msg = ASCIIEncoding.ASCII.GetString(client.GetMessage(i).RawMessage);


        System.IO.File.WriteAllText(@"d:\\My File2.log", msg);
        var body = System.IO.File.ReadLines(@"d:\\My File2.log");
        if (body.Contains("cusotmer ID: X"))
        {
            getemailadress();
            sendemail();
        }
    }
}

还有,建议:停止调用 .ToString() 已经是字符串对象。

而且我无法理解您为什么尝试将 messageBody 保存到 TextFile。因为 WriteAllText 函数会在每个循环中覆盖这个文件。 所以你不会找到这个方法的所有消息结束。您只能在文本文件中找到最后一条消息正文。你注意到了吗?

【讨论】:

  • 我正在尝试将 messageBody 保存到 TextFile,因为我需要从这个 messageBody 中选择特定的单词。
  • 我仍然认为您不需要将 messageBody 保存到任何文件中。您可以在内存中查找、选择或操作您的 messageBody。
猜你喜欢
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 2015-07-21
相关资源
最近更新 更多