To send email from Java, add the Jakarta Mail API and an implementation, set the mail.smtp.* properties for your server, create a Session with an Authenticator, build a MimeMessage and call Transport.send(). For port 587 enable STARTTLS and require it; for port 465 enable mail.smtp.ssl.enable so TLS starts at connect. Always set connection, read and write timeouts.
Jakarta Mail is the successor of JavaMail, now maintained under the Eclipse Foundation, and uses the jakarta.mail package instead of javax.mail. This guide gives complete examples for plain text, HTML, attachments and error handling. If you use Spring Boot, the framework wraps all of this; see Spring Boot email with JavaMailSender.
Add the dependencies
Jakarta Mail separates the API from the implementation. For Maven, add the API and the Eclipse Angus implementation. Check Maven Central for the current versions, since the numbers below are examples of the 2.x line.
<dependency>
<groupId>jakarta.mail</groupId>
<artifactId>jakarta.mail-api</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.angus</groupId>
<artifactId>angus-mail</artifactId>
<version>2.0.3</version>
</dependency>If you are on an older project that still uses javax.mail, the same code works with the package names changed; do not mix the two namespaces on one classpath. Frameworks that still bundle the legacy API, such as older application servers, can cause confusing class conflicts, so check which one is in use.
Send a plain-text email over STARTTLS
import jakarta.mail.*;
import jakarta.mail.internet.*;
import java.util.Properties;
public class SendMail {
public static void main(String[] args) throws MessagingException {
final String host = System.getenv("SMTP_HOST");
final String user = System.getenv("SMTP_USER");
final String pass = System.getenv("SMTP_PASS");
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");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.ssl.checkserveridentity", "true");
props.put("mail.smtp.connectiontimeout", "15000");
props.put("mail.smtp.timeout", "30000");
props.put("mail.smtp.writetimeout", "30000");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]", "Example App", "UTF-8"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
message.setSubject("Your report is ready", "UTF-8");
message.setText("Hello, your report is ready to download.", "UTF-8");
Transport.send(message);
}
}The constructor InternetAddress(String, String, String) can throw UnsupportedEncodingException, so in real code declare or handle it. The timeouts are essential: the defaults are infinite, and a stalled server would otherwise hang the calling thread forever. Use Session.getInstance(), not getDefaultInstance(), because the default session is shared across the JVM and keeps the first credentials it saw.
Implicit TLS on port 465
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.checkserveridentity", "true");With ssl.enable the client wraps the socket in TLS immediately. Do not also enable STARTTLS on this port. If you must trust an internal certificate authority, add it to the Java trust store or supply a custom SSLContext; do not use mail.smtp.ssl.trust=*, which accepts any certificate and removes the protection TLS is meant to give. The differences between the two modes are explained in SMTP settings, ports and authentication.
| Port | Properties | Behaviour |
|---|---|---|
| 587 | starttls.enable and starttls.required | Connect in plain text, upgrade, then authenticate |
| 465 | ssl.enable | TLS from the first byte |
| 25 | Server to server; usually blocked from clients | Avoid for application submission |
HTML body with a text alternative and an attachment
import java.io.File;
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
message.setSubject("Invoice 1001", "UTF-8");
// Text and HTML alternatives
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("Your invoice is attached.", "UTF-8");
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<p>Your invoice is <strong>attached</strong>.</p>", "text/html; charset=UTF-8");
MimeMultipart alternative = new MimeMultipart("alternative");
alternative.addBodyPart(textPart);
alternative.addBodyPart(htmlPart);
MimeBodyPart alternativeWrapper = new MimeBodyPart();
alternativeWrapper.setContent(alternative);
// Attachment
MimeBodyPart attachment = new MimeBodyPart();
attachment.attachFile(new File("/var/app/invoices/1001.pdf"));
attachment.setFileName("invoice-1001.pdf");
MimeMultipart mixed = new MimeMultipart("mixed");
mixed.addBodyPart(alternativeWrapper);
mixed.addBodyPart(attachment);
message.setContent(mixed);
Transport.send(message);The structure matters: a mixed multipart holds the message body and the attachments, and the body is itself an alternative multipart holding the text and HTML versions. Put the plain text first and the HTML last, since clients prefer the last part they can display. For a deeper look at multipart nesting see MIME multipart explained. attachFile() sets the content type and encoding from the file; check the resulting type for unusual extensions.
Handle exceptions
try {
Transport.send(message);
} catch (AuthenticationFailedException e) {
// 535 or similar: wrong credentials or policy
log.error("SMTP authentication failed: {}", e.getMessage());
} catch (SendFailedException e) {
// some or all recipients rejected
log.error("Invalid: {} Valid unsent: {}", (Object) e.getInvalidAddresses(), (Object) e.getValidUnsentAddresses());
} catch (MessagingException e) {
// connection, TLS, timeout or protocol problem
log.error("Mail failure", e);
}AuthenticationFailedException and SendFailedException are subclasses of MessagingException, so catch them first. A SendFailedException lists which addresses were invalid, which were valid but unsent and which were sent, so you can retry only the unsent ones. The nested cause of a MessagingException often tells you more than the message: look at getNextException() and getCause() for socket and SSL errors. Retry temporary 4xx failures with backoff and do not retry 5xx; see rate limits, retries and backoff.
Debugging
- Call
session.setDebug(true)to print the SMTP dialogue to standard output, or set the propertymail.debug=true. Remove it in production and never share the output unredacted, since the AUTH exchange contains your credentials in encoded form. - Reproduce the connection outside Java with
openssl s_client -starttls smtp -connect host:587; see testing an SMTP connection. - If the failure is
PKIX path building failed, the Java trust store lacks the issuer. Update the JDK or import the correct CA certificate, not a blanket trust option. - Make sure the JVM supports a TLS version the server offers; very old runtimes may not negotiate TLS 1.2 or 1.3.
Send many messages over one connection
try (Transport transport = session.getTransport("smtp")) {
transport.connect(host, user, pass); // one TLS handshake and one login
for (MimeMessage m : messages) {
try {
transport.sendMessage(m, m.getAllRecipients());
} catch (SendFailedException e) {
log.warn("Skipping failed message: {}", e.getMessage());
}
}
}Opening a new connection for each message costs a TCP connect, a TLS handshake and an authentication round trip. For batches, obtain a Transport from the session, connect once and call sendMessage() repeatedly. Transport implements AutoCloseable, so try-with-resources closes it. Providers commonly limit how many messages one connection may carry and how fast you may send, so cap the batch size, reconnect when the server closes the session, and slow down on 4xx replies instead of retrying immediately. Run batches on a worker, not on a request thread, and log the queue identifier the server returns for each accepted message so that support requests can be traced.
Note that sendMessage() does not call saveChanges() for you the way Transport.send() does. If you modify a message after building it, call message.saveChanges() first, or the headers such as Message-ID may be missing or stale.
Character encoding and message identity
Pass UTF-8 explicitly when setting the subject, the text and the personal part of an address. Without it, non-ASCII characters in names and subjects can be encoded with the platform default charset, which differs between machines and produces mojibake in the recipient mailbox. Jakarta Mail chooses a transfer encoding (7bit, quoted-printable or base64) based on the content, so you rarely need to set one by hand. Two header choices affect deliverability: keep the From address on a domain you have authenticated, and use a real Reply-To when replies should go somewhere else, via message.setReplyTo(). If your provider lets you set a bounce address, the envelope sender comes from the property mail.smtp.from, which is separate from the visible From header. The difference between the envelope sender and the From header matters for bounce handling and SPF alignment.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| AuthenticationFailedException: 535 | Wrong credentials, or the account needs an app password or API key | Check username, password and authentication method. See error 535 |
| Could not connect to SMTP host | Wrong host or port, firewall, or outbound SMTP blocked | Test with openssl s_client; try the other port |
| SocketTimeoutException: Read timed out | No timeout tuned, slow server or TLS mode mismatch | Match port and mode; set timeouts. See timeouts and TLS errors |
| STARTTLS is required but not supported | Wrong port or server does not offer STARTTLS | Use the submission port, or SSL on 465 |
| PKIX path building failed | Untrusted certificate chain | Install the correct CA in the trust store |
| NoClassDefFoundError for jakarta or javax classes | Namespace or implementation mismatch | Use one namespace and one implementation |
| Strange characters | No charset set | Pass "UTF-8" to setSubject and setText |
Operational tips
- Do not create a new thread per email; use a bounded executor or a queue so slow mail does not exhaust threads.
- For many messages, use one
Transportobtained fromsession.getTransport("smtp"), callconnect()once, thensendMessage()repeatedly andclose()at the end. - Keep credentials in environment variables or a secrets manager, never in the repository. Authenticate your From domain; see authenticating your sending domain.
- Validate addresses before building messages and never place unvalidated input in headers.
- Consider an HTTP email API where outbound SMTP ports are blocked; see SMTP versus API.
Next steps
Start with the plain-text example against a test mailbox, add timeouts and TLS verification, then the multipart structure for HTML and attachments. When it works, move the code behind a small interface so the rest of your application never touches Jakarta Mail directly, and add tests that assert on the built message. If you send through MigoSMTP, use smtp.migosmtp.com with port 587 (STARTTLS) or 465 (implicit TLS) and the credentials from your account.
Relay Java application mail with delivery events Send through MigoSMTP over TLS and track bounces and complaints.
References and further reading
Frequently asked questions
How do I send email in Java?
Add Jakarta Mail and an implementation, configure mail.smtp properties, create a Session with an Authenticator, build a MimeMessage and call Transport.send().
What is the difference between JavaMail and Jakarta Mail?
Jakarta Mail is the Eclipse Foundation successor of JavaMail. Version 2.x uses the jakarta.mail package, while older versions use javax.mail.
How do I enable TLS for SMTP in Java?
Use mail.smtp.starttls.enable and mail.smtp.starttls.required on port 587, or mail.smtp.ssl.enable on port 465. Also set mail.smtp.ssl.checkserveridentity to true.
How do I add an attachment?
Create a MimeBodyPart, call attachFile() with the file, and add it to a mixed MimeMultipart alongside the message body.
Why does my Java mail code hang?
The default timeouts are infinite. Set mail.smtp.connectiontimeout, mail.smtp.timeout and mail.smtp.writetimeout in milliseconds.