Learn to send emails using the Jakarta Mail API and using the Gmail SMTP Server. We will see the Java examples to send plain text emails as well as emails with attachments.
1. Gmail SMTP Server Details
Google has provided free access to one of its SMTP servers and we can use its Java code to send emails.
Gmail SMTP server: smtp.gmail.com
Port: 465 (SSL required) / 587 (TLS required)
Username: Gmail id
Password: The app password
We must create the app password as described in this guide. We cannot use the Gmail password (used to signin in the browser) if we have enabled the 2-factor authentication for the account.
In absense of App password, you will get the “AuthenticationFailedException: 534-5.7.9 Application-specific password required.” error in runtime.
2. Jakarta Mail API
For a typical client application, we need to perform the following steps to send an email:
Create a mail message containing the message header and body
Create a Session object, which authenticates the user using the Authenticator, and controls access to the message store and transport.
Send the message to its recipient list.
3. Maven
Start with adding the following dependencies to the project. Note that the Angus Mail implementation of Jakarta Mail Specification 2.1+ providing a platform-independent and protocol-independent framework to build mail and messaging applications.
A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies.
An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Comments