Wednesday 30 January 2013

C#: Send a simple E-Mail via. Google Gmail SMTP Server



Here's a code snippet which allows you to send an E-Mail using Gmails SMTP server...



Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Mail;
  6. using System.Text;
  7.  
  8. /// <summary>
  9. /// Simple Emailer class for sending a simple email.
  10. /// </summary>
  11. public class Emailer
  12. {
  13.     /// <summary>
  14.     /// Takes a users email and item name and generates an email
  15.     /// </summary>
  16.     /// <param name="recipient">Recipients e-mail address</param>
  17.     public static void SendMail(string recipient)
  18.     {
  19.         try
  20.         {
  21.             // Setup mail message
  22.             MailMessage msg = new MailMessage();
  23.             msg.Subject = "Email Subject";
  24.             msg.Body = "Email Body";
  25.             msg.From = new MailAddress("FROM Email Address");
  26.             msg.To.Add(recipient);
  27.             msg.IsBodyHtml = false; // Can be true or false
  28.  
  29.             // Setup SMTP client and send message
  30.             using (SmtpClient smtpClient = new SmtpClient())
  31.             {
  32.                 smtpClient.Host = "smtp.gmail.com";
  33.                 smtpClient.EnableSsl = true;
  34.                 smtpClient.Port = 587; // Gmail uses port 587
  35.                 smtpClient.UseDefaultCredentials = false; // Must be set BEFORE Credentials below...
  36.                 smtpClient.Credentials = new NetworkCredential("Gmail username", "Gmail Password");
  37.                 smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
  38.                 smtpClient.Send(msg);
  39.             }
  40.         }
  41.         catch (SmtpFailedRecipientsException sfrEx)
  42.         {
  43.             // TODO: Handle exception
  44.             // When email could not be delivered to all receipients.
  45.             throw sfrEx;
  46.         }
  47.         catch (SmtpException sEx)
  48.         {
  49.             // TODO: Handle exception
  50.             // When SMTP Client cannot complete Send operation.
  51.             throw sEx;
  52.         }
  53.         catch (Exception ex)
  54.         {
  55.             // TODO: Handle exception
  56.             // Any exception that may occur during the send process.
  57.             throw ex;
  58.         }
  59.     }
  60. }
End of Code Snippet