Send emails from GMail

Tags: #<Tag:0x00007f0b762c1bf8>

Sending emails from gmail using smtp protocol requires “Less secure apps” to be enabled in Google account. Otherwise you must use Google REST API.
Suppose you have a project in Google developer console which enables GMail library. Also suppose you already recieved an access token to this project.
Below is code snippet to send an email from gmail account using GMail service:

SendMail                      PROCEDURE(STRING pAccessToken, STRING pFrom, STRING pTo, STRING pSubject, STRING pBody)
curl                            TCurlClass
res                             CURLcode
dsResponse                      &IDynStr
endpoint                        STRING('')
sMessage                        ANY
  !Next 2 options are the same as curl.AddHttpHeader('Authorization: Bearer '& pAccessToken)
  curl.SetOpt(CURLOPT_XOAUTH2_BEARER, pAccessToken)
  curl.AddHttpHeader('Accept: application/json')
  curl.AddHttpHeader('Content-Type: message/rfc822')

  dsResponse &= NewDynStr()

  !- build the message comnpliant with the RFC822 standard
  sMessage = printf('From: %s%|To: %s%|Subject: %s%|%|%s', pFrom, pTo, pSubject, pBody)
  res = curl.SendRequest(endpoint, sMessage, dsResponse)
  IF res = CURLE_OK
    ParseResponse(dsResponse.Str(), errResp)
    IF errResp.ErrCode = 0
      MESSAGE('Success!', 'SendMail', ICON:Asterisk)
      MESSAGE(printf('Error: %i%|Status: %s%|Message: %s', errResp.ErrCode, errResp.ErrStatus, errResp.ErrMessage), 'SendMail', ICON:Exclamation)
  ELSIF res = -1
    MESSAGE('SendRequest failed: errcode '& res, 'SendMail', ICON:Asterisk)
    MESSAGE('SendRequest failed: '& curl.StrError(res), 'SendMail', ICON:Exclamation)

Note: anyone who has 2FA enabled on their google account cannot use “less secure apps”.

I had this situation for a customer and ended up having to write a small python app that my clarion app calls when sending email. It’s based on the example code google provides and implementation followed the process in their examples. Perhaps there’s a way to build that in-between code with your curl add on.

But you can generate application passwords for your app, and use them to bypass the 2FA.

True, but that doesnt work for gsuite users - and thanks for pointing that out, as the clarification is important to some.