Friday 11 July 2014

Using C# with Gmail - Part 2, SMTP

POP3 isn't actually natively supported in .NET, but as has been shown, it's pretty easy to do. Next up is SMTP. This is much simpler as .NET has this built into the System.Net.Mail class.

Sending email


Really, the only thing hard about sending email is getting things in the correct order... Here I've the send email method as an event - it would be very simple to write a wrapper around it

This event is linked to a very simple winform which you can see if you download the source code

void SendClick(object sender, EventArgs e)
{
   MailMessage mail = new MailMessage();
   mail.To.Add("second_user@gmail.com");


It's always a good idea to say who you're email is from. Nice thing here is that if you have a wrapper around the SMTP code, you can email different people. For my example here, I just wanted to email another user account to ensure it works. When you do this sort of thing, having a second account always helps...

   mail.From =
      new System.Net.Mail.MailAddress("your_username@gmail.com");
   if (subject.Text.Length != 0)
      mail.Subject = subject.Text;
   else
      mail.Subject = "I forgot to fill it in";


While there is nothing that says you must have a subject, it's a good idea to. Quite a lot of email spam blockers user a NULL in the message as a fairly high scorer on the factors when it decides if email is spam or not

   mail.Body = message.Text;

If you had any attachments can be added on here. Effectively, this is the header of the email done. Now all that needs to be done is to send it
   
   System.Net.Mail.SmtpClient smtp =
       new System.Net.Mail.SmtpClient("smtp.gmail.com");
   smtp.EnableSsl = true;
   smtp.Credentials =
       new System.Net.NetworkCredential("your_username",
                                        "your_password");
   try
   {
      smtp.Send(mail);
   }
   catch (System.Net.Mail.SmtpException ex)
   {
      MessageBox.Show(ex.Message.ToString(),
                      "Unable to connect to the remote server",
                      MessageBoxButtons.OK);
      return;
   }
}

I did say it wasn't difficult!

No comments:

Post a Comment