Sending Email
Java can send email using the Jakarta Mail API (formerly JavaMail) over the SMTP protocol. Email is an important component in many applications — notifications, account verification, automated reports, and more.
Properties are configured for the SMTP server (host, port, authentication). A Session is created from those properties. MimeMessage builds the email with recipient, subject, and body. Transport.send() sends the email over SMTP.
For SMTP via Gmail, use an App Password (not your main account password), because Gmail requires OAuth2 or an App Password for third-party access. Port 587 for STARTTLS, port 465 for SSL/TLS.
Jakarta Mail Components:
| Class | Use |
|---|---|
Properties |
SMTP configuration |
Session |
Email session |
MimeMessage |
Email message |
Transport |
Send the email |
MimeBodyPart |
Message parts (text, attachments) |
Code Example
import jakarta.mail.*;
import jakarta.mail.internet.*;
import java.util.Properties;
public class SendEmail {
static void sendEmail(String to, String subject, String body) {
// SMTP configuration
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Authentication
Session session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"[email protected]", "app_password_here");
}
});
try {
// Build the message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setText(body);
// Send
Transport.send(message);
System.out.println("Email sent successfully to " + to);
} catch (MessagingException e) {
System.err.println("Failed to send email: " + e.getMessage());
}
}
public static void main(String[] args) {
sendEmail(
"[email protected]",
"Welcome!",
"Your account has been created. Welcome aboard!"
);
}
}
Code Explanation
- SMTP Properties:
mail.smtp.hostis the SMTP server address. Gmail:smtp.gmail.com, Outlook:smtp.office365.com. Port 587 for STARTTLS (recommended). - Authenticator: returns the username and App Password (not your main account password). Generate an App Password in Google Account > Security > 2FA.
- MimeMessage: the
setFrom(),setRecipients(),setSubject(), andsetText()methods build the email step by step. - Transport.send(): sends the email synchronously. Throws a MessagingException if it fails.
Everyday Example
Automated notification email with an attachment:
import jakarta.mail.*;
import jakarta.mail.internet.*;
import java.util.Properties;
public class EmailNotification {
static void sendNotification(String to, String name, String orderId)
throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
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("[email protected]", "app_pass");
}
});
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
msg.setSubject("Order Confirmation #" + orderId);
// HTML body
String html = """
<h2>Terima kasih, %s!</h2>
<p>Order <b>#%s</b> is being processed.</p>
<p>Estimated delivery: 2-3 business days.</p>
""".formatted(name, orderId);
msg.setContent(html, "text/html; charset=utf-8");
Transport.send(msg);
System.out.println("Notification sent to " + to);
}
public static void main(String[] args) throws Exception {
sendNotification("[email protected]", "John", "ORD-2026-001");
}
}
Summary
The Jakarta Mail API is the standard for sending email in Java. For production applications, consider using JavaMail with an SMTP relay (SendGrid, Mailgun) or the Spring Boot Starter Mail, which simplifies configuration. Always use an App Password rather than your main account password for security.