Sending Email With the GMail API

This article shows how to send emails using the GMail API.

Date Entered: 11/07/2014    Last Updated: 11/07/2014

The GoogleRequest component makes it possible to easily implement any Google API that is not directly supported by our Google Integrator. This article will demonstrate how to use our GoogleRequest component, OAuth component, and MIME component to send an email using Google's GMail API.

There are three steps to sending an email using Google's GMail API.

  1. Obtain an authorization token using the OAuth component.
  2. //Getting an authorization string oauth1.ClientId = "723966830965.apps.googleusercontent.com"; oauth1.ClientSecret = "_bYMDLuvYkJeT_99Q-vkP1rh"; oauth1.ServerAuthURL = "https://accounts.google.com/o/oauth2/auth"; oauth1.ServerTokenURL = "https://accounts.google.com/o/oauth2/token"; oauth1.AuthorizationScope = "https://mail.google.com/"; string authorization = oauth1.GetAuthorization();
  3. Construct the email itself using the MIME component.
  4. Mime mime = new Mime(); mime.Parts.Add(new MIMEPart()); mime.Parts[0].ContentType = "text/plain"; mime.Parts[0].DecodedString = "This is a test email."; mime.Parts.Add(new MIMEPart("C:\\Path\\To\\Attachment.txt")); mime.EncodeToString(); mime.MessageHeadersString = "To: somuser@somewhere.com\r\nFrom: me@myemail.com\r\nSubject: GMail test.\r\n" + mime.MessageHeadersString;
  5. Send the GMail request using the GoogleRequest component.
  6. Googlerequest req = new Googlerequest(); //Note: The "authorization" variable here contains the //OAuth Authorization String from Step 1. req.Authorization = authorization; req.ContentType = "message/rfc822"; req.PostDataB = System.Text.Encoding.Default.GetBytes(mime.MessageHeadersString + "\r\n\r\n" + mime.Message); req.Post("https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=media");


We appreciate your feedback.  If you have any questions, comments, or suggestions about this entry please contact our support team at kb@nsoftware.com.