When I develop in C#, there are a lot of seemingly simple tasks that are incredibly hard to figure out how to develop.
Sending and receiving email from code is one of those things. It takes trial & error and a reading a lot of other blogs while piecing things together. So to help you NOT waste time, here are the basics…
Sending
Sending email is built into C#, so there's no 3rd party library requirement. You'll be hitting up the SmtpClient class (in System.Net.Mail) and NetworkCredential (in System.Net).
For these demos, I'm using a gmail account with a custom domain… [email protected]… So no, I'm not actually setting up a smtp server or pop server… that's only for people who love pain.
Here's how you send an email:
var message = new MailMessage("[email protected]", "[email protected]");
message.Subject = "What Up, Dog?";
message.Body = "Why you gotta be all up in my grill?";
SmtpClient mailer = new SmtpClient("smtp.gmail.com", 587);
mailer.Credentials = new NetworkCredential("[email protected]", "YourPasswordHere");
mailer.EnableSsl = true;
mailer.Send(message);
Just drop in your own info for the message. Then update the network credentials to match your gmail login. If you're using gmail, then you're golden… but make sure you keep the "EnableSsl" flag as true. If you're not using gmail, drop in the SMTP server and possibly change the port.
A pretty fantastic thing for all you Java Hippies is that you can configure the SmtpClient from the web.config… so just new one up and you're ready to go. Except I'm kinda lying because you can't set "EnableSsl" from the web.config.
Receiving
Receiving is a bit more complicated. It does require a 3rd party library. I tried to get it working with Google's GData API but the best I ever got was an xml feed of my inbox. And parsing xml is only for people who like to waste time.
So after 3-4 failed libraries, I finally got OpenPOP to work. If you're using GMail, you may find IMAP better than POP since gmail has folders and POP doesn't. The wording on that sentence was fantastic. You're welcome.
Here's the code to get the subject of the latest email in your inbox:
var client = new POPClient();
client.Connect("pop.gmail.com", 995, true);
client.Authenticate("[email protected]", "YourPasswordHere");
var count = client.GetMessageCount();
Message message = client.GetMessage(count);
Console.WriteLine(message.Headers.Subject);
I'd like to be able to do more searching and querying when I receive email, but this gets the job done.
Wanna know a secret? Here's there reason I wanted to receive email. I have some automation running with selenium and sometimes a captcha pops up. In that case, I take a screenshot and email it to myself. Then, at my convenience, I reply to the email with the text I see in the captcha. Selenium types it in and continues. Pretty bad to the bone, huh?
