To read Gmail emails in Java, you must use the Jakarta Mail API (formerly JavaMail) and connect via the IMAP protocol using an App Password. Because Google blocks standard password authentication for third-party apps, you cannot use your primary account password; you must generate a unique 16-character app-specific password from your Google Account security settings to establish a secure connection.

What You'll Need

  • Java Development Kit (JDK) installed on your machine.
  • An Integrated Development Environment (IDE) like IntelliJ IDEA, Eclipse, or NetBeans.
  • The Jakarta Mail (javax.mail) library dependency.
  • A Gmail account with 2-Step Verification enabled.
  • A generated Google App Password.

Step-by-Step

  1. Enable IMAP in Gmail: Log into your Gmail account via a web browser. Click the gear icon for Settings and select "See all settings". Navigate to the "Forwarding and POP/IMAP" tab. In the IMAP access section, select "Enable IMAP". Click "Save Changes" at the bottom of the page. This allows external Java applications to communicate with the Gmail server to retrieve messages.
  2. Set Up 2-Step Verification: Go to your Google Account security settings. Under the "How you sign in to Google" section, ensure that 2-Step Verification is turned on. This is a mandatory prerequisite for creating an App Password.
  3. Generate an App Password: In the security settings, search for "App passwords". Give your app a name (e.g., "JavaEmailReader") and click "Create". Google will display a 16-character code in a yellow box. Copy this code immediately, as it will not be shown again. This password bypasses the need for OAuth2 for simple scripts, though OAuth2 is recommended for production-grade software.
  4. Add Dependencies to Your Project: If you are using Maven, add the following dependency to your pom.xml file. If you are not using a build tool, you must manually download the jakarta.mail.jar and add it to your project's classpath.
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>jakarta.mail</artifactId>
        <version>1.6.7</version>
    </dependency>
  5. Configure Session Properties: In your Java code, create a Properties object to define the connection settings. You must specify the IMAP host (imap.gmail.com), the port (993), and enable SSL (Secure Sockets Layer). These settings ensure that the communication between your Java app and Google's servers is encrypted.
    Properties props = new Properties();
    props.put("mail.store.protocol", "imaps");
    props.put("mail.imaps.host", "imap.gmail.com");
    props.put("mail.imaps.port", "993");
    props.put("mail.imaps.ssl.enable", "true");
  6. Establish the Store Connection: Use the Session class to create a store. Pass your Gmail address and the 16-character App Password you generated earlier. Call the connect() method to authenticate with the server.
    Session session = Session.getInstance(props);
    Store store = session.getStore("imaps");
    store.connect("your-email@gmail.com", "your-app-password");
  7. Access the Inbox Folder: Once connected, open the "INBOX" folder. Use the store.getFolder("INBOX") method and call folder.open(Folder.READ_ONLY). Using read-only mode is a safety precaution that prevents your code from accidentally deleting or marking emails as read while you are testing.
  8. Retrieve and Read Messages: Use folder.getMessages() to get an array of all emails in the inbox. You can then loop through this array. For each Message object, use getMessageByFolder() or getContent() to extract the subject line and the body of the email. If the email is a Multipart message, you will need to iterate through the body parts to find the text content.
  9. Close Resources: Always close the folder and the store in a finally block to avoid memory leaks and to ensure the connection to the Gmail server is terminated properly.
    folder.close(false);
    store.close();

Common Mistakes

One of the most frequent errors is attempting to use the primary Google account password. Because of Google's security policies, this will result in an AuthenticationFailedException. You must use an App Password. Another common mistake is forgetting to enable IMAP in the Gmail settings. Even with the correct password, the server will reject the connection if IMAP is disabled.

Developers often struggle with Multipart email bodies. Many emails are sent as a combination of plain text and HTML. If you simply call getContent() on a multipart message, you will receive an object of type MimeMultipart rather than a string. You must check if the content is an instance of Multipart and then loop through the parts to extract the actual text.

Hardcoding credentials directly into the source code is a significant security risk. If the code is pushed to a public repository like GitHub, the App Password will be exposed, allowing anyone to access your emails. Always use environment variables or a separate .properties file that is excluded from version control via .gitignore.

Tips

To improve performance, avoid downloading the entire message body if you only need the subject line. Use the Message.getSubject() method first. If the subject matches a specific keyword, only then should you call getContent() to fetch the full body. This reduces bandwidth and speeds up the execution of your program.

For better organization, use the folder.search() method instead of retrieving all messages. Jakarta Mail provides a SearchTerm class that allows you to filter emails by sender, date, or subject. For example, you can create a search for only unread messages or messages received within the last 24 hours, which prevents your application from processing thousands of old emails every time it runs.

When dealing with large volumes of email, implement a pagination strategy. Instead of calling getMessages(), which retrieves everything, use getMessages(int start, int end) to process emails in smaller batches (e.g., 50 at a time). This prevents OutOfMemoryError exceptions in your Java Virtual Machine (JVM).

Troubleshooting

If you encounter a javax.mail.AuthenticationFailedException, first verify that 2-Step Verification is active and that you are using a fresh App Password. If the password was entered correctly and it still fails, double-check that you haven't accidentally included spaces in the password string.

If the connection times out or you see a MessagingException related to the connection, check your network's firewall or antivirus settings. Some corporate networks block port 993. You can test if the port is open by using a command-line tool like telnet imap.gmail.com 993. If the connection fails there, the issue is with your network, not your Java code.

If you are seeing strange characters or symbols in the email body, it is likely an encoding issue. Use message.getContent().toString() and ensure your IDE is set to UTF-8 encoding. For complex emails, you may need to use a library like Jsoup to parse the HTML content and strip out the tags to get clean text.

If you receive a "Too many connections" error, it means your application is opening stores and folders without closing them. Ensure that every store.connect() is paired with a store.close() inside a finally block to release the connection back to the Gmail server.

Frequently Asked Questions

Do I need to pay for an API key to read Gmail emails?

No, using the IMAP protocol with Jakarta Mail is free. You only need a standard Gmail account and an App Password. API keys are only required if you use the official Google Gmail API via OAuth2.

Is IMAP better than POP3 for Java applications?

Yes, IMAP is generally preferred because it syncs with the server. This means you can read emails without deleting them from the server, and you can manage folders. POP3 typically downloads the email and removes it from the server, which is less flexible.

Can I read emails from a Google Workspace account?

Yes, the process is identical for Workspace accounts. However, your organization's administrator must have IMAP access enabled at the domain level in the Google Admin console before you can enable it in your individual settings.

How do I handle attachments in Java?

Attachments are handled as parts of a MimeMultipart message. You must iterate through the body parts, check if a part is an attachment using part.getDisposition(), and then use part.saveFile("filename") to save the attachment to your local disk.

Will this code work if I change my main Google password?

Changing your main password usually does not invalidate your App Passwords immediately, but for security reasons, it is recommended to delete and regenerate your App Passwords whenever you update your primary account credentials.