Search code examples
gmailgmail-api

Using `gmail.send` scope with SMTP MSA


Scope https://www.googleapis.com/auth/gmail.send does not let me send email using GMail SMTP with this log (I send mail with PHPMail):

Connection: opening to smtp.gmail.com:587, timeout=300, options=array ()
Connection: opened
SERVER -> CLIENT: 220 smtp.gmail.com ESMTP za2sm18821308wjb.34 - gsmtp
CLIENT -> SERVER: EHLO example.com
SERVER -> CLIENT: 250-smtp.gmail.com at your service, [94.115.154.79]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
CLIENT -> SERVER: STARTTLS
SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
CLIENT -> SERVER: EHLO example.com
SERVER -> CLIENT: 250-smtp.gmail.com at your service, [94.115.154.79]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
CLIENT -> SERVER: AUTH XOAUTH2 dXNlcj1tYXJ0aW5AZHp1YmFrLnNrAWF1dGg9QmVhcmVyIHlhMjkuQ2k5TEE0REJCMDdxOGVBVkpGT3FQRGlyQVRhTlBJcWVPb3d5RjdmekY2QTZqcG9Za3hxQjZLZFVzSkVISTdXWjlnAQE=
SERVER -> CLIENT: 334 eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==
SMTP ERROR: AUTH command failed: 334 eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==
SMTP Error: Could not authenticate.
CLIENT -> SERVER: QUIT
SERVER -> CLIENT: 535-5.7.8 Username and Password not accepted. Learn more at535 5.7.8 https://support.google.com/mail/answer/14257 za2sm18821308wjb.34 - gsmtp
SMTP ERROR: QUIT command failed: 535-5.7.8 Username and Password not accepted. Learn more at535 5.7.8 https://support.google.com/mail/answer/14257 za2sm18821308wjb.34 - gsmtp
Connection: closed
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

I tried to add all other gmail scopes except full access scope, still did not work. However, it will work when I add full access scope https://mail.google.com/. Any idea why? I do not want give my script full access to GMail...


Solution

  • The send scope is only documented to work on the Gmail API (HTTP REST interface). If you want to use SMTP yes, it only accepts the full mail scope.

    There is a Google API php client library you can use to handle a lot of this logic. To do this without using client library refer to this doc if you haven't seen it.

    If sending < 5MB can send to POST https://www.googleapis.com/gmail/v1/users/userId/messages/send

    You need to set the following two HTTP headers on your request:

    • Authenication (oauth2 token)
    • Content-Type: "application/json"

    What you should POST is a "message" having a raw field that is base64url encoded, something like (pardon the python pseudo-code):

    message = {}
    message['raw'] = base64.url_encode("To: you\r\nFrom: me\r\nSubject: test\r\n\r\nbody goes here")
    httplib.POST(url, json.dumps(message), required_headers)`