JavaMail: Sending Email in Java

Harry · 11 Sep 2026 · 10 views

What is JavaMail?

JavaMail (jakarta.mail / javax.mail) is the standard Java API to send and receive email using SMTP, POP3 and IMAP. With it, your application can send welcome emails, password resets, invoices and notifications.

JavaMail API overview

Minimum Dependencies

  • jakarta.mail (or javax.mail) - the API.
  • jakarta.activation - used for data handlers.

Sending a Text Email

import jakarta.mail.*;
import jakarta.mail.internet.*;
import java.util.Properties;

public class SendMail {
    public static void main(String[] args) throws Exception {
        String host = "smtp.gmail.com";
        String from = "you@gmail.com";
        String password = "app-password";
        String to = "friend@example.com";

        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getInstance(props,
            new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from, password);
                }
            });

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject("Hello from JavaMail");
        message.setText("This email was sent from a Java program.");

        Transport.send(message);
        System.out.println("Email sent.");
    }
}

HTML Emails

message.setContent("<h1>Welcome!</h1><p>Thanks for signing up.</p>", "text/html; charset=utf-8");

Key Points

  • SMTP credentials are secrets - keep them in environment variables or a config server.
  • Gmail and most providers expect an app password, not your account password, for SMTP.
  • Use TLS/STARTTLS on port 587 for sending through providers.
Share this post:

Comments (0)

Please login or register to comment.