Sample code for 30+ languages & platforms
Java

SMTP XOAUTH2 Authentication

See more SMTP Examples

Demonstrates how to authenticate using an OAuth2 access token. This example assumes you have already obtained the access token and now wish to use it in an SMTP session.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.MailMan;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        String oauth2_access_token = "some_previously_obtained_token";

        MailMan mailman = new MailMan();

        // Set the properties for the SMTP server, whatever they may be..
        mailman.setSmtpHost("smtp.example.com");
        mailman.setSmtpPort(587);
        mailman.setStartTLS(true);

        mailman.setSmtpUsername("myLogin");
        mailman.setOAuth2AccessToken(oauth2_access_token);

        // Create a new email object
        Email email = new Email();

        email.setSubject("This is a test");
        email.setBody("This is a test");
        email.setFrom("Joe Example <joe@example.com>");
        email.addTo("Chilkat Admin", "admin@chilkatsoft.com");

        // Connect to the server indicated by the SmtpHost property
        try {
            mailman.smtpConnect();

            // Authenticate using XOAUTH2 (using the OAuth2AccessToken)
            mailman.smtpAuthenticate();

            mailman.sendEmail(email);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("Email sent.");

        mailman.closeSmtpConnection();
    }
}