1

你们看到这个 C# 代码有什么问题吗?它从 gmail 获取电子邮件通知,然后向 CMD 打印有多少未读邮件正在等待:

Unread Mails: 10
Unread Mails: 10

然后也通过串行发送多少邮件。但是在它说“未读邮件:”两次之后,我得到:

Operation Timed Out.
Unread Mails: 0

它重复。

我已经在不同的计算机和 ISP 上尝试过这个,所以它肯定在代码中。C# 程序。我也尝试过更改 Thread.Sleep 值,以便在它再次执行之前需要更长的时间,但仍然无法正常工作。谢谢!

public static void Main(string[] args)
    {
        try 
        {
            SerialPort port = new SerialPort( "COM1", 9600, Parity.None, 8, StopBits.One );
            port.Open();

            string Unreadz = "0";
            while ( true )
            {
                Unreadz = CheckMail();
                Console.WriteLine("Unread Mails: " + Unreadz);
                if (Convert.ToInt32(Unreadz) < 10) port.Write("0" + Unreadz);
                else port.Write("" + Unreadz);

                System.Threading.Thread.Sleep( 10000 );
            }
        } catch ( Exception ee ) { Console.WriteLine( ee.Message ); }

    }

    public static string TextToBase64( string sAscii ) 
    {
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        byte[] bytes = encoding.GetBytes( sAscii );
        return System.Convert.ToBase64String( bytes, 0, bytes.Length );
    }

    public static string CheckMail() 
    {
        string result = "0";

        try 
        {
            var url = @"https://gmail.google.com/gmail/feed/atom";
            var USER = "USER";
            var PASS = "PASS";

            var encoded = TextToBase64( USER + ":" + PASS );

            var myWebRequest = HttpWebRequest.Create( url );
            myWebRequest.Method = "POST";
            myWebRequest.ContentLength = 0;
            myWebRequest.Headers.Add( "Authorization", "Basic " + encoded );

            var response = myWebRequest.GetResponse();
            var stream = response.GetResponseStream();

            XmlReader reader = XmlReader.Create( stream );
            while ( reader.Read())
                if ( reader.NodeType == XmlNodeType.Element )
                    if ( reader.Name == "fullcount" ) 
                    {
                        result = reader.ReadElementContentAsString();
                        return result;
                    }
        } catch ( Exception ee ) { Console.WriteLine( ee.Message ); }
          return result;
    }

}

}

4

1 回答 1

0

好吧,我似乎修好了。因为我只是每 10 秒循环一次进行测试,所以我把它设置为 5 分钟。5 分钟更符合我的需求。

于 2011-08-27T03:05:10.747 回答