Sample code for 30+ languages & platforms
PureBasic Requires Chilkat v11.0.0+

Gmail SMTP: Send Email with OAuth2

See more GMail SMTP/IMAP/POP Examples

Send an email through smtp.gmail.com:587 with STARTTLS and an OAuth2 access token. Chilkat constructs the SASL XOAUTH2 authentication exchange; do not put the access token in SmtpPassword. Port 465 with implicit TLS is an alternative.

This example sends a real email. Set the mailbox to the account that authorized the token and use a recipient you control. The From address is that mailbox; another address must be an authorized Gmail send-as identity. Gmail normally saves SMTP submissions in Sent, so do not automatically append another copy through IMAP.

SMTP acceptance does not prove inbox delivery. Account sending limits, recipient limits, spam filtering, and Workspace policies still apply. A connection failure after message data was transmitted can leave the result uncertain; blind retries can create duplicate mail. Authentication/session logs can contain credentials and message data.

This example reads gmail-mail-token.json from a private working directory. Authorize the account first, then refresh the access token before it expires. The separate filename avoids confusing this full-mail grant with a narrower Gmail REST token. Store credentials in protected application storage; never distribute a user's token file with an application.

Gmail SMTP, IMAP, and POP3 use the https://mail.google.com/ OAuth scope. Narrower Gmail REST scopes such as gmail.send or gmail.readonly do not authorize these protocols. Public applications using this restricted scope must meet Google's verification requirements. See Gmail OAuth scopes and XOAUTH2.

Google documentation

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkJsonObject.pb"
IncludeFile "CkEmail.pb"
IncludeFile "CkMailMan.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Assumes Chilkat is unlocked. See Global Unlock Sample.

    token.i = CkJsonObject::ckCreate()
    If token.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoadFile(token,"gmail-mail-token.json")
    If success <> 1
        Debug "Could not read gmail-mail-token.json from the private working directory."
        CkJsonObject::ckDispose(token)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(token,"access_token") <> 1) OR (CkJsonObject::ckStringOfEquals(token,"access_token","",1) = 1)
        Debug "An OAuth access token is required. Authorize or refresh the account first."
        CkJsonObject::ckDispose(token)
        ProcedureReturn
    EndIf

    mailbox.s = "user@example.com"
    mailman.i = CkMailMan::ckCreate()
    If mailman.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkMailMan::setCkSmtpHost(mailman, "smtp.gmail.com")
    CkMailMan::setCkSmtpPort(mailman, 587)
    CkMailMan::setCkSmtpSsl(mailman, 0)
    CkMailMan::setCkStartTLS(mailman, 1)
    CkMailMan::setCkRequireSslCertVerify(mailman, 1)
    ;  Alternative: port 465 with SmtpSsl=true and StartTLS=false (implicit TLS).
    CkMailMan::setCkSmtpUsername(mailman, mailbox)
    CkMailMan::setCkSmtpPassword(mailman, "")
    CkMailMan::setCkOAuth2AccessToken(mailman, CkJsonObject::ckStringOf(token,"access_token"))

    email.i = CkEmail::ckCreate()
    If email.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkEmail::setCkFrom(email, mailbox)
    CkEmail::setCkSubject(email, "Sample message")
    CkEmail::setCkBody(email, "This message was sent through Gmail SMTP using OAuth2.")
    success = CkEmail::ckAddTo(email,"Recipient","recipient@example.net")
    If success <> 1
        Debug "Could not add the recipient."
        CkJsonObject::ckDispose(token)
        CkMailMan::ckDispose(mailman)
        CkEmail::ckDispose(email)
        ProcedureReturn
    EndIf

    ;  This sends a real message. Replace the recipient with an address you control.
    success = CkMailMan::ckSendEmail(mailman,email)
    If success <> 1
        CkMailMan::ckCloseSmtpConnection(mailman)
        Debug "SMTP send failed. Check the token, mailbox, recipient, and Gmail sending limits."
        ;  Inspect LastErrorText privately if needed; do not publish authentication/session logs.
        ;  A lost connection after DATA can leave acceptance uncertain. Avoid blindly retrying.
        CkJsonObject::ckDispose(token)
        CkMailMan::ckDispose(mailman)
        CkEmail::ckDispose(email)
        ProcedureReturn
    EndIf

    success = CkMailMan::ckCloseSmtpConnection(mailman)
    If success <> 1
        Debug "Gmail accepted the message, but closing the connection failed. Do not resend it."
        CkJsonObject::ckDispose(token)
        CkMailMan::ckDispose(mailman)
        CkEmail::ckDispose(email)
        ProcedureReturn
    EndIf

    Debug "Gmail accepted the message for delivery."


    CkJsonObject::ckDispose(token)
    CkMailMan::ckDispose(mailman)
    CkEmail::ckDispose(email)


    ProcedureReturn
EndProcedure