Reader Level:
ARTICLE

Relay Email Using Your Gmail Account

Posted by Scott Lysle Articles | Visual Studio 2012 September 19, 2012
This article describes a quick and easy way to test your email messages by relaying them through your existing Gmail account.
  • 1
  • 0
  • 5109

Introduction

This article describes a quick and easy way to test your email messages by relaying them through your existing Gmail account. This can be useful if you wish to test the appearance of an email message as delivered to an email account or just the entire work flow of a project that requires sending an email message. I would not recommend relaying all of an application's email messages through a Gmail account; in production you should send your messages through a properly configured SMTP server.

This article includes a class containing the code necessary to send an email message through your production SMTP server and to send your emails through your Gmail account for testing purposes or until you have the appropriate SMTP server configured for use. The package also includes a Windows Forms test application that you can use to send a test message through your Gmail account.

gmail-relay.jpg

Figure 1: Test Application

Getting Started

In order to begin, unzip the downloaded files and open the project provided. Within the project you will find a simple Win Forms application written in C#; the application contains a single form used to collect the information needed to send an email. The application was built using Visual Studio 2012; the code would work equally well with Visual 2010.

The project also contains a class file entitled, "EmailHandler.cs". This file contains the code to send an email with or without attachments using either your SMTP server or an existing Gmail account.

The Code: EmailHandler.cs

Open this class file to examine its content. The class is divided into three regions, the code in each region applies to sending the message using an SMTP server or using a Gmail account, the last region contains utility code applicable to either set of code, in this case, the code contained there executes a regular expression test to validate that an email address is properly formatted.

The test application will use the code contained in this class to send an email message through a Gmail account. The code in the SMTP region won't be discussed herein, it works basically the same way as the Gmail specific code works but it is not tailored specifically to work with the required Gmail settings.

Looking at the Gmail code region you will find two methods, one to send an email message with attachments, and one to send an email message without attachments. If you need to send email messages with attachments, you might want to also examine the files, obtain their file sizes, and make certain that the target email account can handle messages large enough to accommodate the attachments. If you are not certain of the maximum allowable message sizes, as a rule of thumb it is a good idea to keep the total size of the message to below 5 MB as that is a common default setting. A simple example of checking the attachment accumulated file sizes is included in the demonstration application.

The first function contained in the Gmail section of the class is used to send a message without any attachments. The code follows and it is annotated to describe it:

public static string SendMessageThroughGmail(string sendTo, string sendFrom, string sendSubject, string sendMessage, string yourGmailAddress, string yourGmailPassword)

{

      try

      {

          // validate the email address

          // against a regular expression

          bool bTest = ValidateEmailAddress(sendTo);

 

          // if the email address is bad, return message

          if (bTest == false)

              return "Invalid recipient email address: " + sendTo;

 

          // create the email message

          MailMessage message = new MailMessage(

             sendFrom,

             sendTo,

             sendSubject,

             sendMessage);

 

          // create smtp client

          SmtpClient client = new SmtpClient();

          client.UseDefaultCredentials = false;

          // create network credentials using the

          // gmail user ID (the email address) and the

          // gmail password

          client.Credentials =

              new System.Net.NetworkCredential(yourGmailAddress,

yourGmailPassword);

          client.Host = "smtp.gmail.com"; // fixed for gmail

          client.Port = 587; // gmail setting

          client.EnableSsl = true // required for gmail relay

 

          // send message

          client.Send(message);

 

          return "OK";

      }

      catch (Exception ex)

      {

          return ex.Message.ToString();

      }

  }

 The next code block is the same with the exception of accepting an array list of file paths representing the message attachments. It is also annotated to describe the contents.

public static string SendMessageWithAttachmentThroughGmail(string sendTo, string sendFrom, string sendSubject, string sendMessage, ArrayList attachments, string yourGmailAddress, string yourGmailPassword)

{

    try

    {

        // validate email address

        bool bTest = ValidateEmailAddress(sendTo);

 

        if (bTest == false)

            return "Invalid recipient email address: " + sendTo;

 

        // Create the basic message

        MailMessage message = new MailMessage(

           sendFrom,

           sendTo,

           sendSubject,

           sendMessage);

 

        // The attachments array should point to a file location    

        // where the attachment resides - add the attachment(s)

        // to the message

        foreach (string attach in attachments)

        {

            Attachment attached = new Attachment(attach,

            MediaTypeNames.Application.Octet);

            message.Attachments.Add(attached);

        }

 

        // create smtp client

        SmtpClient client = new SmtpClient();

        client.UseDefaultCredentials = false;

        client.Credentials = new System.Net.NetworkCredential(yourGmailAddress,

yourGmailPassword);

        client.Host = "smtp.gmail.com";

        client.Port = 587;

        client.EnableSsl = true;

 

        // send message

        client.Send(message);

 

        return "OK";

    }

    catch (Exception ex)

    {

        return ex.Message.ToString();

    }

}

The remainder of the code contained in this class is again either used to send email using your SMTP server or is used to validate the format of an email address using a regular expression. Refer to that code within the project to examine those parts.

Refer to the attached example application to test the class and see it in use. You can also review the code used to attach the file attachments in order to see one approach to testing the file attachment size to see if you need to warn the user about an oversized attachment.

COMMENT USING

Trending up