Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Using the Jakarta Mail API directly (not Spring), send an HTML email with a PDF attachment through an SMTP server that requires STARTTLS and authentication.

We create a Properties object with the SMTP host, port 587, mail.smtp.auth=true, mail.smtp.starttls.enable=true and mail.smtp.starttls.required=true, plus connection and read timeouts, and build a Session with an Authenticator. Then we build a MimeMessage with sender, recipients and subject, whose content is a MimeMultipart holding an HTML MimeBodyPart and a PDF part added with attachFile, and we send it with Transport.send(message). The code uses the jakarta.mail packages, with an implementation such as Eclipse Angus Mail on the classpath.

Why this question is asked

Even in Spring applications, it helps to know the raw Jakarta Mail API, because Spring's JavaMailSender is a thin layer over it and every mail problem we debug shows up in its terms: sessions, MIME parts and transports. Interviewers ask for this code to see whether we understand how an email with an attachment is structured and whether we think about security and timeouts. In this answer, we will recap how SMTP and MIME fit together, configure the session, build the message with its parts, send it, and then look at the dependencies and the timeouts that keep threads from hanging.

1A Quick Recap of SMTP, STARTTLS and MIME

SMTP (Simple Mail Transfer Protocol) is how our application hands an email to a mail server. Port 587 is the submission port for clients. The connection starts as plain text, and STARTTLS is a command that upgrades the same connection to an encrypted TLS connection before we send the password or the message. Because an attacker in the middle could remove the STARTTLS offer, we tell Jakarta Mail to require it, so it fails instead of falling back to plain text.

MIME (Multipurpose Internet Mail Extensions) is the format that lets one email carry several parts. An email with HTML text and a PDF is a multipart message: one body part has the type text/html, the other has application/pdf with a file name, and both are wrapped in a multipart container of subtype mixed. Jakarta Mail models this directly with MimeMessage, MimeMultipart and MimeBodyPart.

2Adding the Dependencies

Since Jakarta Mail 2.1, the API and the implementation are separate artifacts. The API jar contains the interfaces and classes we compile against, and Eclipse Angus Mail, the successor of the old reference implementation, contains the SMTP provider that actually talks to the server. We need both at runtime.

XML
<!-- Maven: versions current at the time of writing; check your version -->
<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>

Notice the package names in what follows: jakarta.mail and jakarta.mail.internet. Old code written for Java EE uses javax.mail, and it must be changed to the jakarta names when it moves to current libraries.

3Writing the Sender

Here is the complete program. The comments show what each part produces.

Java
import jakarta.mail.*;
import jakarta.mail.internet.*;
import java.io.File;
import java.util.Date;
import java.util.Properties;
public class InvoiceMailer {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true"); // send AUTH with user and password
props.put("mail.smtp.starttls.enable", "true"); // upgrade to TLS
props.put("mail.smtp.starttls.required", "true"); // fail if the server does not offer it
props.put("mail.smtp.connectiontimeout", "10000"); // 10 s to connect
props.put("mail.smtp.timeout", "10000"); // 10 s per read
props.put("mail.smtp.writetimeout", "10000"); // 10 s per write
String user = System.getenv("SMTP_USER");
String password = System.getenv("SMTP_PASSWORD"); // never hard-coded
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("billing@example.com", "Example Billing"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("ana@example.org"));
msg.setSubject("Your invoice 42", "UTF-8");
msg.setSentDate(new Date());
MimeBodyPart html = new MimeBodyPart();
html.setContent("<h1>Invoice 42</h1><p>Total: 120.00 EUR</p>", "text/html; charset=UTF-8");
MimeBodyPart pdf = new MimeBodyPart();
pdf.attachFile(new File("invoice-42.pdf"), "application/pdf", null); // file name: invoice-42.pdf
MimeMultipart mixed = new MimeMultipart("mixed");
mixed.addBodyPart(html); // part 1: text/html
mixed.addBodyPart(pdf); // part 2: application/pdf
msg.setContent(mixed);
Transport.send(msg); // connect, STARTTLS, AUTH, MAIL FROM, RCPT TO, DATA, QUIT
}
}
Step throughWhat Transport.send does on the wire
AppJakarta MailSMTP server
Transport.send(msg)
connect to port 587, EHLO
250 STARTTLS, AUTH offered
STARTTLS, then TLS handshake
AUTH with credentials from the Authenticator
MAIL FROM, RCPT TO, DATA with MIME body
250 queued
returns, or throws MessagingException

8 messages in order. Play them, or step through them one at a time.

The Session holds the configuration and the authenticator. When Transport.send runs, it asks the session for the SMTP transport, connects to the host, issues STARTTLS, calls our authenticator for the credentials, sends the message and closes the connection. The reason we pass the content type explicitly to attachFile is that otherwise the type is guessed from the file name through a type map, which may return application/octet-stream on some setups.

4Why the Timeouts Matter

By default, Jakarta Mail waits forever to connect and forever for each response. If the SMTP server becomes slow or a firewall silently drops packets, every thread that sends mail blocks indefinitely. In a web application, that can use up the whole request thread pool, and the application stops answering even pages that have nothing to do with email.

So we always set mail.smtp.connectiontimeout, mail.smtp.timeout and mail.smtp.writetimeout, in milliseconds. With 10 seconds each, a stuck server costs a thread at most a few tens of seconds and the code gets a MessagingException it can retry or log. In a real application, we would also send mail from a background worker or queue rather than inside the user's request, so even a slow server never delays the response.

5Common Mistakes

Three mistakes appear often. The first is using port 465 with STARTTLS settings: port 465 expects TLS from the first byte, which needs mail.smtp.ssl.enable=true instead. The second is sending HTML without a charset, which breaks accented names; we set charset=UTF-8 on the HTML part and on the subject. The third is keeping only jakarta.mail-api on the classpath, which compiles fine but fails at runtime because no SMTP provider is present.

6Follow-up questions

How would you add a plain-text alternative for clients that do not show HTML?

We put a MimeMultipart of subtype alternative inside the mixed one. The alternative part holds a text/plain body part first and the text/html part second, and the client shows the last one it can display. The PDF stays as a sibling in the outer mixed multipart.

Should we reuse a Transport for many emails?

For bulk sending, yes. Transport.send opens and closes a connection for every message. For many messages we can call session.getTransport("smtp"), connect once, call sendMessage for each message with its recipients, and close it at the end, which saves a handshake per email.

How do we embed an image in the HTML instead of attaching it?

We use a multipart of subtype related, add the image as a body part with a Content-ID header, and reference it from the HTML with src="cid:logo". Many clients block remote images, so inline images display more reliably.

7Conclusion

In this answer, we saw that sending an HTML email with a PDF through an authenticated STARTTLS server takes a Session configured with host, port 587, auth, required STARTTLS and timeouts, a MimeMessage whose content is a mixed MimeMultipart with an HTML part and an attached PDF, and a call to Transport.send. The code uses the jakarta.mail packages with Angus Mail as the implementation, and the timeouts protect our threads from a slow SMTP server.

What to say in the interviewAbout 70 seconds aloud

Open with

I would start with a Properties object: mail.smtp.host, port 587, mail.smtp.auth set to true, and both mail.smtp.starttls.enable and mail.smtp.starttls.required set to true, so the connection is upgraded to TLS and never falls back to plain text.

Then, if they want more

I would also set mail.smtp.connectiontimeout, mail.smtp.timeout and mail.smtp.writetimeout, because the defaults wait forever and a slow server would block threads. Then I create the Session with Session.getInstance, passing an Authenticator that returns a PasswordAuthentication with credentials from the environment or a secret store.

For the message, I create a MimeMessage, call setFrom with an InternetAddress, setRecipients with Message.RecipientType.TO, and setSubject with UTF-8.

The content is a MimeMultipart of subtype mixed with two MimeBodyParts: one with setContent of the HTML and the type text/html with charset UTF-8, and one where I call attachFile with the PDF and the content type application/pdf, which also sets the file name. Then Transport.send(message) connects, does STARTTLS and AUTH, and sends it.

On dependencies, I use the jakarta.mail packages: jakarta.mail-api plus an implementation such as Eclipse Angus Mail, because since 2.1 the API jar has no SMTP provider. Old javax.mail code needs the namespace change.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Jakarta EE specifications
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Using the Jakarta Mail API directly (not Spring), send an HTML email with a PDF...": https://scrivio-interview-library.netlify.app/java/jakarta-ee-platform/61d8381ff5/