Sending Email From a Gmail Account with C# .NET and Web Services

Introduction

Sending email notifications from C# ASP .NET web applications can often become a troublesome process. Automatic emails from software may be marked as junk or spam by many ISP mail servers. This can make it difficult for users to properly receive email notifications from software products and the messages themselves can be very important to the user. While one solution may be to ask users to add your web applications email address to their junk mail filter’s safe-list, this process can be difficult to control and unreliable. A possibly better solution is to use a 3rd-party email service to route messages through, such as Gmail.

In this article, we’ll create a basic C# ASP .NET web service which sends emails using Gmail’s SMTP server and your own Gmail account. The web service that we’ll create can by used by any range of applications, written in any programming language, simply by communicating with the web service in XML to send emails.

Why Gmail?

Gmail is one of the most popular web-based email services around, next to Hotmail and Yahoo, and also has one of the best deliverability rates and junk mail filtering systems. These features make Gmail a good choice as a 3rd-party email provider and even for sending programmatic emails and software notifications from web services, C# ASP .NET web applications, and desktop software, when used responsibly. Gmail provides the ability to route email through the Gmail SMTP server, using your Gmail account, and keep the From and Reply-To address listed as your own email address. With this feature, your C# ASP .NET web applications can send email automatically through Gmail, but use your own (non-Gmail) email address as the sender. This allows you to continue using your own email address for software-based notifications, but avoid any marking as spam that sending through your own domain’s SMTP server might encounter.

Creating Your Gmail Account and Linking to Your Domain

The first step to creating our Gmail emailing web service is to setup a Gmail account to act as our primary email account for our C# ASP .NET web application. The steps to create a Gmail account and setup your own (non-Gmail) email address as the sender and reply-to are listed below:

  1. Visit http://www.gmail.com and create an account.

  2. Once created, log in and click Settings along the top right menu.

  3. Click the Accounts tab.

  4. Click “Add another email address you own”.

  5. Enter your own (non-Gmail) email address and fill in the Reply-to address as well.

  6. Verify your email address with gmail and it should be added to your account.

  7. Back in the Accounts tab, find your newly added email address and click “Make Default”.

  8. Select the radio button for “Always reply from default address”.

It’s also a good idea to click the Forwarding tab and select the radio button for “Forward a copy of incoming mail to” and specify your (non-Gmail) email address. This way you’ll receive any email sent specifically to the gmail account at your standard email address, such as Mailer Daemon messages, bounce-backs, or message failures.

With your Gmail account created and setup to send email as your own domain’s email address, we’re ready to move on to creating the C# ASP .NET web service to send the emails.

Getting to Know System.Web.Mail and the MailMessage

System.Web.Mail is one of the more common methods for communicating with SMTP servers to send email from C# ASP .NET web applications. The MailMessage object is the core object for composing messages, populating the sender, recipient, cc, bcc, and other necessary fields for sending email. A typical example for using the MailMessage object to send an email in C# ASP .NET, based upon a contact page in a web application, would be as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
try
{
 if (Request.Form.HasKeys())
 {
   MailMessage mail = new MailMessage();

   mail.To = "johndoe@somewhere.com";
   mail.From = Request.Form["CustomerEmail"] + " (" + Request.Form["CustomerName"] + ")";
   mail.BodyFormat = MailFormat.Text;
   mail.Subject = "C# .NET Web Application Email: " + Request.Form["Subject"];

   int iCount = 0;
   for (int i=0; i<Request.Form.Count; i++)
   {
      string strArg = Request.Form.GetKey(i);
      string strValue = Request.Form.Get(i);
      mail.Body += strArg + ": " + strValue + "\n";
   }

   // Send the mail.
   SmtpMail.SmtpServer = "localhost";
   SmtpMail.Send(mail);
 }
}
catch (Exception excep)
{
   // Error sending email.
}

Note in the above code, we create a new MailMessage object and populate the To, From, Subject, and Body fields to prepare the email message. We then set the SMTP server and send the email. The .NET framework takes care of the details of transmitting the email, which makes the SmtpMail object particularly easy to use.

While sending email to standard SMTP servers is straight-forward with the MailMessage object and the SmtpMail feature, sending email through Gmail’s SMTP server takes a few extra steps, largely for security reasons. Therefore, we’ll need to create our own MailMessage class to specifically handle Gmail email messages.

Hacking the System.Web.Mail.MailMessage

Sending email to standard SMTP servers was quite easy using SmtpMail. However, Gmail’s server requires a secure connection with SSL enabled and requires a special port. To implement these details, we need to create our own GmailMessage class to handle the details of communicating with these security rules in place.

We’ll be using the RC.Gmail class, which inherits from System.Web.Mail.MailMessage to handle the secure communication with Gmail’s SMTP server.

The code below is an excerpt from the helper class. The entire Gmail helper class can be downloaded in full at CSharpGmail or the download page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
 public class GmailMessage : System.Web.Mail.MailMessage
 {
  private static string _gmailServer = "smtp.gmail.com";
  private static long _gmailPort = 465;
  private string _gmailUserName = string.Empty;
  private string _gmailPassword = string.Empty;

  ...

  /// <summary>
  /// Constructor, creates the GmailMessage object
  /// </summary>
  /// <param name="gmailUserName">The username of the gmail account that the message will be sent through</param>
  /// <param name="gmailPassword">The password of the gmail account that the message will be sent through</param>
  public GmailMessage(string gmailUserName, string gmailPassword)
  {
   this.Fields[SMTP_SERVER] = GmailMessage.GmailServer;
   this.Fields[SMTP_SERVER_PORT] = GmailMessage.GmailServerPort;
   this.Fields[SEND_USING] = 2;
   this.Fields[SMTP_USE_SSL] = true;
   this.Fields[SMTP_AUTHENTICATE] = 1;
   this.Fields[SEND_USERNAME] = gmailUserName;
   this.Fields[SEND_PASSWORD] = gmailPassword;

   _gmailUserName = gmailUserName;
   _gmailPassword = gmailPassword;
  }

  /// <summary>
  /// The username of the gmail account that the message will be sent through
  /// </summary>
  public string GmailUserName
  {
   get { return _gmailUserName; }
   set { _gmailUserName = value; }
  }

  /// <summary>
  /// The password of the gmail account that the message will be sent through
  /// </summary>
  public string GmailPassword
  {
   get { return _gmailPassword; }
   set { _gmailPassword = value; }
  }

  #region Static Members

  /// <summary>
  /// Sends an email through the specified gmail account
  /// </summary>
  /// <param name="gmailUserName">The username of the gmail account that the message will be sent through</param>
  /// <param name="gmailPassword">The password of the gmail account that the message will be sent through</param>
  /// <param name="toAddress">Recipients email address</param>
  /// <param name="subject">Message subject</param>
  /// <param name="messageBody">Message body</param>
  public static void SendFromGmail(string gmailUserName, string gmailPassword, string toAddress, string subject, string messageBody)
  {
   try
   {
    GmailMessage gMessage = new GmailMessage(gmailUserName, gmailPassword);

    gMessage.To = toAddress;
    gMessage.Subject = subject;
    gMessage.Body = messageBody;
    gMessage.From = gmailUserName;
    if(gmailUserName.IndexOf('@') == -1) gMessage.From += "@Gmail.com";

    System.Web.Mail.SmtpMail.Send(gMessage);
   }
   catch(Exception ex)
   {
    //TODO: Add error handling
    throw ex;
   }
  }

  ...

  #endregion

 } //GmailMessage

The first item to note in the above code is that the class inherits from MailMessage. This allows the class to function almost exactly like a MailMessage object when sending emails. The specialized differences for sending email through Gmail is most notably apparent in the constructor, where we set the Gmail SMTP server to smtp.gmail.com, the port to 465, and the required security flags for sending emails in C# .NET using SSL (secure sockets layer) and authentication. Note, the authentication portion uses the Gmail account username and password as the valid login to send emails. With the MailMessage custom configuration complete, we can use the underlying MailMessage object as we would normally, by simply filling in the From, To, Subject, and Body properties and sending the MailMessage. Once again. the .NET framework takes care of the details of talking to Gmail’s SMTP server in secure mode and on port 465.

With our customized Gmail MailMessage class complete, we can now begin sending emails.

Sending Email Through Gmail

Just as we did with the standard MailMessage class, we can send Gmail messages using similar client code, implementing our new GmailMessage class, as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
try
{
// Use the GmailMessage object to create and send your message using our outside registered from address.
RC.Gmail.GmailMessage gmailMsg = new RC.Gmail.GmailMessage("YourGmailUsername", "YourGmailPassword");
gmailMsg.To = "johndoe@somewhere.com";
gmailMsg.From = "YourRegisteredEmailAddressWithGmail@YourDomain.com"; // registered with gmail to send on our behalf
gmailMsg.Subject = "Hello World!";
gmailMsg.Body = "Send from C# ASP .NET.\nHello World!";
gmailMsg.Send();
}
catch (Exception excep)
{
// Error sending email.
}

Note the above code is very similar to our initial client code for sending emails with MailMessage. The only difference is that we instantiate the GmailMessage object and populate it accordingly. It’s also important to note that if you’ve registered an outside email address with your Gmail account in order to send emails from a different email address other than the Gmail account, you’ll need to provide that email address in the From field. You’ll also need to pass your Gmail account login information into the constructor of the GmailMessage, for authentication with Gmail. With the client code complete, you should be able to send email through Gmail from your C# ASP .NET web application.

Email is Nice, But Where’s the Web Service?

The client code has been completed and we can now send emails through Gmail in C# ASP .NET, using a secure connection and customized SMTP port. However, we can enhance this functionality much further and provide Gmail emailing capabilities to all of our web applications, in many different programming languages, by providing a web service containing the client code. Our custom applications could then send email through Gmail, using the same method, by simply communicating with XML to invoke the C# ASP .NET web service. Note, for simplicity, the web service code below is not setup to use SSL, https, or other web service network security. You may wish to further enhance the web service’s security before using in production.

To begin, we can create a web service GmailMailer.asmx.cs as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/// <summary>
/// Summary description for GmailMailer
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class GmailMailer : System.Web.Services.WebService
{
    [WebMethod]
    public string GmailSend(string authKey, string to, string from, string subject, string body)
    {
        if (authKey != "yourreallylongpassword")
        {
            return "ERROR";
        }

        try
        {
            //Use the GmailMessage object to create and send your message using our outside registered from address.
            RC.Gmail.GmailMessage gmailMsg = new RC.Gmail.GmailMessage("YourGmailUsername", "YourGmailPassword");
            gmailMsg.To = to;
            gmailMsg.From = from; // registered with gmail to send on our behalf
            gmailMsg.Subject = subject;
            gmailMsg.Body = body;
            gmailMsg.Send();

            return "OK";
        }
        catch (Exception excep)
        {
            return "ERROR: " + excep.Message;
        }
    }
}

The above code is the framework for a C# .NET web service. Our web service contains a single method GmailSend() which takes the necessary information for sending an email and an authentication key. While the code for sending the email through Gmail (inside the try/catch block) is the same as previously shown in our client code example, it’s important to note the authenitcation key (authkey) check at the beginning of the method. While this helps prevent misuse of the web service, there are several more ways to better protect the web service and, in practice, you may wish to include these further security validations to make the service more secure.

Speaking Our Language with C

Visual Studio allows us to easily invoke a web service method by referencing the web service in the Visual Studio project and instantiating the client object. To do this, simply right-click the project name in Visual Studio and select Add Service Reference. Enter the URL pointing to your .asmx web service (created in the steps above). Visual Studio will automatically create a client class to handle instantiating the C# .NET web service, as follows:

1
2
3
4
5
6
7
8
9
10
GmailMailerSoapClient gmailMailer = new GmailMailerSoapClient();
string result = gmailMailer.GmailSend("yourreallylongpassword", "johndoe@somewhere.com", "YourRegisteredEmailAddressWithGmail@YourDomain.com", "Hello World!", "Send from C# ASP .NET.\nHello World!");
if (result.IndexOf("ERROR") > -1)
{
// Report error sending Gmail.
}
else
{
// Email successfully sent.
}

Visual Studio makes it very easy to call the web service method with the above client code and send emails through Gmail from your C# ASP .NET web applications. However, what if you have applications written in other programming languages that you wish to have send emails through Gmail as well? Rather than re-write the Gmail emailing class code in the other languages, we can call the same C# ASP .NET web service by sending an XML SOAP packet and verifying the result.

Communicating with our .NET Web Service in CGI Perl

As an example of communicating with our C# ASP .NET web service using a different programming language other than C# .NET, we’ll take the example of wanting to send email through Gmail using a CGI script or Perl. Therefore, we’ll need to call the .NET web service with CGI Perl and SOAP XML.

You’ll first need to create a CGI Perl client stub to invoke the C# .NET web service. In the case of CGI Perl, we can create the following method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/perl

use LWP::UserAgent;

# ...

sub sendEmail {
  ($to, $subject, $body) = @_;

  # Build XML post request.
  $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  $xml .= "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n";
  $xml .= " <soap:Body>\n";
  $xml .= "   <GmailSend xmlns=\"http://tempuri.org/\">\n";
  $xml .= "     <authKey>[AUTHKEY]</authKey>\n";
  $xml .= "     <to>[TO]</to>\n";
  $xml .= "     <from>[FROM]</from>\n";
  $xml .= "     <subject>[SUBJECT]</subject>\n";
  $xml .= "     <body>[BODY]</body>\n";
  $xml .= "   </GmailSend>\n";
  $xml .= " </soap:Body>\n";
  $xml .= "</soap:Envelope>\n";

  # Replace in our variables into the XML packet.
  $xml =~ s/\[AUTHKEY\]/yourreallylongpassword/g;
  $xml =~ s/\[TO\]/$to/g;
  $xml =~ s/\[FROM\]/YourRegisteredEmailAddressWithGmail\@YourDomain.com/g;
  $xml =~ s/\[SUBJECT\]/$subject/g;
  $xml =~ s/\[BODY\]/$body/g;

  # Call the web service method to send the gmail.
  $ua = new LWP::UserAgent;
  $req = new HTTP::Request 'POST','http://www.yoursite.com/services/GmailMailer.asmx';
  $req->content_type('text/xml');
  $req->content($xml);
  $res = $ua->request($req);

  # Verify the response.
  if ($res->is_error)
  {
     // Error sending email.
     $error_as_html = $res->error_as_HTML;
  }
  else
  {
     // The request was successful. Verify $result is OK.
     $result = $res->content;
  }
}

We can call the above CGI Perl code to send email with Gmail through our C# ASP .NET web service with the following line of CGI Perl code:

1
sendEmail("johndoe\@somewhere.com", "Hello World!", "Send from C# ASP .NET.\nHello World!");

There are a vast number of different programming languages which can utilize the C# ASP .NET web service for sending email notifications with Gmail. They simply need to be able to support posting a SOAP XML packet to a remote URL. C# .NET web services make it easy to communicate with web applications written in other languages, such as CGI Perl, PHP, ColdFusion, C, C++, and many more.

Conclusion

C# ASP .NET web applications often require sending email notifications from within the software to users requesting information or feedback. While some ISP mail servers may reject messages as junk or spam, Gmail provides an easy and potentially more reliable alternative SMTP server for sending email notifications from C# .NET applications. Communicating with Gmail’s SMTP server requires customizing the C# .NET MailMessage object to use a secure connection and custom port 465 to send emails through. By wrapping the Gmail email class within a C# .NET web service, we can share the functionality of Gmail email notification with our various applications written in many different programming languages, simply by posting an XML packet to the web service URL.

About the Author

This article was written by Kory Becker, software developer and architect, skilled in a range of technologies, including web application development, machine learning, artificial intelligence, and data science.

Share