我的Gmail通知程序代码有什么问题?

时间:2011-08-22 20:56:25

标签: gmail notify

你们看到这个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;
    }

}

}

1 个答案:

答案 0 :(得分:0)

好吧,我似乎解决了这个问题。因为我只是每10秒循环一次进行测试,所以我把它放到5分钟。 5分钟对我的需求更为现实。