What is wrong with my Gmail notifier code?
Do you guys see any issues with this C# code? It gets email notifications from gmail and then prints to CMD how many unread mails are waiting:
Unread Mails: 10
Unread Mails: 10
and then sends how many mails over serial too. But after it says "unread mails:" twice i get:
Operation Timed Out.
Unread Mails: 0
and it repeats.
Iv'e tried this on different computers and ISPs so its definitely something in the code. The C# program. I also have tried changing the Thread.Sleep value so that it takes longer before it does it again, 开发者_StackOverflow中文版but still doesn't work. Thanks!
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;
}
}
}
well i seemed to fix it. since i was just looping it every 10 seconds for testing, i put it to 5 minutes. 5 minutes is more realistic for my needs.
精彩评论