Using gmail as an smtp client

Things new to me. Letting my C# application send an email.

How would that be easily done? – Well. There is a handy namespace called System.Net.Mail
First I created a class called EmailMessage to hold the message specific data, and added a nice little constructor to that.

	class EmailMessage
	{
		public string To { get; set; }
		public string From { get; set; }
		public string Subject { get; set; }
		public string Message { get; set; }

		public EmailMessage(string to, string from, string subject, string message)
		{
			To = to;
			From = from;
			Subject = subject;
			Message = message;
		}
	}

Then I created a service class with a method to send the message. To be populated with the EmailMessage, some credentials and stuff:


class EmailService
{
public void SendMessage(EmailMessage msg, string username, string password, string host, int port, bool enableSsl)
		{
			var mailMessage = new MailMessage(msg.From, msg.To, msg.Subject, msg.Message);
			var credentials = new NetworkCredential(username, password);
			var smtpClient = new SmtpClient(host, port);
			smtpClient.EnableSsl = enableSsl;
			smtpClient.Credentials = credentials;
			smtpClient.Send(mailMessage);
		}
}

Then what? I asked the IT guy, but he could help me sometime in the future. I was kinda eager to make this code send something to my inbox as soon as possible. Then someone suggested using gmail as smtp server.
So, I created a new account (all the good accounts are already taken, so I had to settle for a bland one). Then I wrote some code to call my EmailService

public void EmailServiceTest1()
		{
			var service = new EmailService();
			var message = new EmailMessage("recipient@somewhere.com", "sender@somewhere.com", "testing emailservice", "testing emailservice from my app, yes I am!");
			service.SendMessage(message, "gmailaccount@gmail.com", "password", "smtp.gmail.com", 587, true);
		}

And that’s about how far I got this time. I will probably abandon all this code as soon as I find something better. But for now it actually does exactly what I want it to.
Last but not least: Beware of code sending emails all over the place. Don’t use real adresses for test purposes!

Posted in Uncategorized | Leave a comment

“This is my church.. This is where I heal my hurts..”

I work as a software developer. Almost everyday I learn some new stuff. That is one of the benefits of this profession. I work mainly with .NET, Scrum and people.

This is where I intend to share some of my thoughts on the subject of learning. Someone might find someting useful here.

 

Posted in Uncategorized | 1 Comment