Skip to content

Instantly share code, notes, and snippets.

@tiesont
Last active January 2, 2016 08:59
Show Gist options
  • Save tiesont/8280201 to your computer and use it in GitHub Desktop.
Save tiesont/8280201 to your computer and use it in GitHub Desktop.
Helper class used to access a Gmail account remotely for the purpose of sending an email message
/// <summary>
/// GmailSender: Class used to access a Gmail account remotely for the purpose of sending an email message
/// </summary>
public class GmailSender
{
/// <summary>
/// Static method. Accepts required elements for sending a email through the Google Mail system.
/// </summary>
/// <param name="to">The target (recipient) of the email message.</param>
/// <param name="subject">Subject line value for the email.</param>
/// <param name="message">The email message body.</param>
/// <param name="isHTML">if set to <c>true</c> [is HTML].</param>
/// <returns>
/// true on successful sent message; false if an exception is thrown
/// </returns>
public static bool SendMail(string to, string subject, string message, bool isHTML)
{
try
{
// Create user credentials
var loginInfo = new NetworkCredential("your-gmail-username", "your-gmail-password");
// Build message
var msg = new MailMessage();
msg.From = new MailAddress("your-gmail-address");
msg.To.Add(new MailAddress(to));
msg.Subject = subject;
msg.IsBodyHtml = isHTML;
msg.Body = message;
// Create the SMTP object and send the message
using (var client = new SmtpClient("smtp.gmail.com"))
{
client.EnableSsl = true;
client.Port = 587;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
return true;
}
}
catch (Exception ex)
{
// TODO: log exception
return false;
}
}
} // end class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment