I wanted to pickup mail messages from my Gmail account programmatically and post them to a blog account. I though I would use POP but in reading Google access options, I found you can pickup your mail as an RSS feel (Atom). I was really excited and got working on it. It turned out to be pretty simple - I used the atom library Atom.Net(C#) once I pulled the feed.
using
System;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
namespace Gmail
{
class AtomClient
{
private WebRequest wrGETURL;
private Stream feedStream;
private string username;
private string password;
public AtomClient(string url, string username, string password)
{
this.username = username;
this.password = password;
feedStream = GetFeedStream(url);
}
private Stream GetFeedStream(string url)
{
byte[] bytes;
wrGETURL = WebRequest.Create(url);
bytes = Encoding.ASCII.GetBytes(username + ":" + password);
wrGETURL.Headers.Add("Authorization", "Basic " +
Convert.ToBase64String(bytes));
return wrGETURL.GetResponse().GetResponseStream();
}
public void GetFeeds()
{
Atom.Core.AtomFeed atomFeed = Atom.Core.AtomFeed.Load(feedStream);
Atom.Core.Collections.AtomEntryCollection entries = atomFeed.Entries;
foreach(Atom.Core.AtomEntry entry in entries)
{
Console.WriteLine(entry.Uri.AbsoluteUri);
//Stream stream = GetFeedStream(entry.Uri.AbsoluteUri);
//WriteStreamToConsole(stream);
}
}
void WriteStreamToConsole(Stream currentStream)
{
//Read the Response Steam.
StreamReader reader = new StreamReader(currentStream);
string responseText = reader.ReadToEnd();
//Close the Stream.
currentStream.Close();
Console.WriteLine(responseText);
}
}
}
The problem was the link pointing to the full message never worked for me. After trying numerous things, I decided to go back to POP. I found a good POP3 library, OpenPOP. The only problem was Google makes you authenticate using SSL. After finding an open source C# library (Org.Mentalis.Security) and integrating it to OpenPOP, I was on my way.
using
System;
using System.Xml;
namespace Gmail
{
class consumer
{
static void Main()
{
OpenPOP.POP3.POPClient popClient = new OpenPOP.POP3.POPClient("pop.gmail.com", 995,
"yourUserAccount@gmail.com", "yourPassword",
OpenPOP.POP3.AuthenticationMethod.TRYBOTH,true);
for (int i=1; i <= popClient.GetMessageCount(); i++)
{
Console.WriteLine("message: " + i);
OpenPOP.MIMEParser.Message msg = popClient.GetMessage(i,false);
string msgStr = string.Empty;
msg.GetMessageBody(msgStr);
Console.WriteLine("RawMessageBody: " + msg.RawMessageBody);
Console.WriteLine("ID: " + msg.MessageID);
Console.WriteLine(
"=================================================");
}
}
}
}
That did it :)
I then did the programmatic posting to the blog and placed that in a service but I will leave that for another day :)