Javamail Api Sending Email From Java

Study guide

Java Mail API: JavaMail Classes, Sending Email from Java with Example and Common Errors

Java mail API and Java email API for CSC419 and BIT401: Session, MimeMessage, Transport, Store, Folder, SMTP vs POP3 and IMAP, a working send-mail program, attachments and port 465 vs 587 errors.

2026-10-24 | notesharu team

"Java mail API" and "Java email API" are two names for one thing: the JavaMail API, a package for sending, receiving and managing email from Java programs. It is set as a short note or a 5 to 10 mark question in the Network Programming unit of TU BSc CSIT Advanced Java Programming (CSC419, unit 5) and appears with sockets in Network Programming with Sockets in BIT401 Advanced Java Programming (unit 7).

This article explains what JavaMail is, its main classes (Session, Message, MimeMessage, Transport, Store, Folder), the protocols behind it, a compact working send-mail program, attachments through Multipart, the common errors, and how a 5 or 10 mark answer is usually written.

What JavaMail is

JavaMail is a platform and protocol independent framework for building mail and messaging applications. It gives Java a standard set of abstract classes for reading and writing messages, and the actual protocols are supplied by providers behind that interface. It is not part of the core JDK. You add the library as a jar (or a Maven dependency), together with the Jakarta Activation framework that it needs for message content types. The package name was javax.mail through version 1.6 and is jakarta.mail in version 2.0 and later, with the same classes.

Protocols

Email uses different protocols for sending and reading. SMTP (Simple Mail Transfer Protocol) is used to send mail from a client to a server and between servers. POP3 (Post Office Protocol) downloads messages from the server to the client, usually removing them from the server. IMAP (Internet Message Access Protocol) lets the client work with messages that stay on the server, with folders and flags. In JavaMail, SMTP is used through a Transport, and POP3 or IMAP through a Store.

TaskProtocolJavaMail class used
Send a messageSMTPTransport
Read, download messagesPOP3 or IMAPStore and Folder

The core classes

Session represents a mail session. It holds the configuration (a Properties object with host, port, authentication and security settings) and an optional Authenticator that supplies a username and password. Every other object is created from a session, so it is always the first object you build.

Message and MimeMessage Message is the abstract class for an email, and MimeMessage is the concrete class for Internet mail. It stores the sender (setFrom), recipients (setRecipients), subject (setSubject) and body (setText or setContent).

Transport sends messages. Transport.send(message) is the simple static method, and an object obtained with session.getTransport("smtp") allows an explicit connect, send and close.

Store represents a message store, such as a mailbox on a POP3 or IMAP server. You get it from session.getStore("imaps") and call connect with host, user and password.

Folder is a folder inside a store, for example INBOX. You call store.getFolder("INBOX"), open it with open(Folder.READ_ONLY), and read messages with getMessages().

Authenticator is a class you extend to return a PasswordAuthentication when the server demands login.

Properties carry keys such as mail.smtp.host, mail.smtp.port, mail.smtp.auth and mail.smtp.starttls.enable.

A minimal send-mail program

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

public class SendMail {
    public static void main(String[] args) {
        final String user = "[email protected]";
        final String pass = "app-password";

        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(user, pass);
            }
        });

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(user));
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("[email protected]"));
            msg.setSubject("Test mail");
            msg.setText("Hello from JavaMail");
            Transport.send(msg);
            System.out.println("Mail sent");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

The program follows the standard order. Set the properties, create the session with an authenticator, build a MimeMessage with sender, recipient, subject and text, and hand it to Transport.send. All JavaMail methods throw MessagingException, so the code sits in a try block. With jakarta.mail, only the import names change to jakarta.mail.

Attachments with Multipart

A message with an attachment is a multipart message. You create a MimeBodyPart for the text, another for the file using attachFile or a DataHandler with a FileDataSource, add both to a MimeMultipart, and set that as the content of the message.

MimeBodyPart text = new MimeBodyPart();
text.setText("Please find the report attached.");

MimeBodyPart file = new MimeBodyPart();
file.attachFile("report.pdf");

Multipart mp = new MimeMultipart();
mp.addBodyPart(text);
mp.addBodyPart(file);
msg.setContent(mp);

Reading mail with Store and Folder

For reading, the sequence is: create a session, get a Store for imaps or pop3s, connect, get the INBOX folder, open it, call getMessages(), print each subject and sender, then close the folder and store. POP3 has only an inbox, while IMAP supports several folders.

Common errors

Authentication failure: AuthenticationFailedException, or a 535 response, means the username or password is wrong. Many providers, Gmail in particular, no longer accept the normal account password for SMTP and require an app password or OAuth, and the account needs two-step verification for app passwords.

Port 465 vs 587: port 587 is the submission port and starts in plain text, then upgrades with STARTTLS, so set mail.smtp.starttls.enable to true. Port 465 uses SSL from the first byte, so set mail.smtp.ssl.enable to true instead. Using the wrong flag with the wrong port gives a connection hang or an SSL handshake error. Port 25 is for server to server mail and is often blocked by providers.

TLS errors: SSLHandshakeException or "Could not convert socket to TLS" usually points to a missing TLS property, an old Java version, or a certificate that is not trusted. Setting mail.smtp.ssl.protocols to TLSv1.2 is a common fix.

Other usual problems: a NoClassDefFoundError because the activation jar is missing, using javax.mail imports with a jakarta.mail jar or the reverse, and AddressException from a badly formed address.

How to write it in the exam

For 5 marks, define JavaMail, name SMTP, POP3 and IMAP, list Session, Message, Transport, Store and Folder with one line each, and give the short program. For 10 marks, add the attachment code, the reading steps with Store and Folder, and the Properties settings, and draw a small diagram of the client, the SMTP server and the POP3 or IMAP server.

The unit notes are on Network Programming in CSC419, with past papers on the CSC419 subject page. BIT students should read Network Programming with Sockets in BIT401 and the BIT401 subject page.

Put it into practice

Browse all subjects