The JavaMail API is a Java API that allows Java applications to send and receive email messages using standard protocols like SMTP, POP3, and IMAP. It provides a platform-independent and protocol-independent framework for building email functionality into Java applications. JavaMail makes it easy to integrate email-sending capabilities, handle attachments, and manage different types of email content.
1. What is JavaMail API?
The JavaMail API provides an abstracted interface to send and receive emails using protocols such as SMTP (Simple Mail Transfer Protocol) for sending emails and POP3 (Post Office Protocol) or IMAP (Internet Message Access Protocol) for receiving emails. JavaMail allows you to:
- Compose, send, and receive emails with attachments.
- Handle different types of email content (plain text, HTML, etc.).
- Manage email connections, sessions, and properties.
2. Key Components of JavaMail API
a) Session
A Session
object represents a mail session and contains properties that specify how the mail system will operate (like SMTP server configuration). A Session
object is typically created with the help of a Properties
object.
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.gmail.com");
Session session = Session.getInstance(properties);
b) Message
The Message
class represents an email message. It includes methods for setting the subject, recipient, content, and headers of the email.
Example:
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender@example.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("receiver@example.com"));
message.setSubject("Test Subject");
message.setText("Hello, this is a test email.");
c) Transport
The Transport
class is used to send the email message to the recipient. It supports methods for connecting to mail servers and sending messages.
Example:
Transport.send(message);
d) InternetAddress
The InternetAddress
class represents an email address. You can use it to set the sender and recipient’s addresses.
InternetAddress fromAddress = new InternetAddress("sender@example.com");
InternetAddress toAddress = new InternetAddress("receiver@example.com");
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, toAddress);
e) MimeMessage
MimeMessage
is a subclass of the Message
class that allows sending complex messages with attachments, HTML content, or alternative body types.
3. Sending Emails using JavaMail API
a) Basic Example of Sending an Email
Here’s a basic example of how to send a simple text email using the JavaMail API and an SMTP server like Gmail.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendEmailExample {
public static void main(String[] args) {
String to = "receiver@example.com"; // Recipient's email ID
String from = "sender@example.com"; // Sender's email ID
String host = "smtp.gmail.com"; // SMTP server
// Set system properties
Properties properties = System.getProperties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "587"); // Gmail uses port 587
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// Get the Session object
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your-email@gmail.com", "your-password");
}
});
try {
// Create a default MimeMessage object
MimeMessage message = new MimeMessage(session);
// Set From header field of the header
message.setFrom(new InternetAddress(from));
// Set To header field of the header
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject header field
message.setSubject("Test Email from JavaMail");
// Set the actual message
message.setText("This is a test email sent using JavaMail API.");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
b) Sending an HTML Email with JavaMail
You can also send HTML emails using JavaMail. You need to set the content type as text/html
.
Example:
message.setContent("<h1>This is a test email with HTML content</h1>", "text/html");
c) Sending an Email with an Attachment
To send an email with attachments, you can use the MimeMultipart
class, which allows combining different types of content (text, HTML, attachments).
Example:
import javax.mail.internet.*;
public class SendEmailWithAttachment {
public static void main(String[] args) {
// SMTP server configuration
String host = "smtp.gmail.com";
String to = "receiver@example.com";
String from = "sender@example.com";
Properties properties = System.getProperties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// Create a session
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your-email@gmail.com", "your-password");
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Test Email with Attachment");
// Create the message part for text content
BodyPart textPart = new MimeBodyPart();
textPart.setText("This email contains an attachment.");
// Create the message part for the attachment
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile("/path/to/file.txt");
// Create the multipart message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(textPart);
multipart.addBodyPart(attachmentPart);
// Set the content of the message
message.setContent(multipart);
// Send the message
Transport.send(message);
System.out.println("Email with attachment sent successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. Common Errors and Troubleshooting
- Authentication Errors: Make sure the correct username and password are used for the SMTP server. In Gmail, you may need to enable “Less Secure Apps” or use an App Password.
- TLS/SSL Issues: Ensure that you are using the correct port and enabling
starttls
if needed. Gmail typically uses port 587 for TLS. - Invalid Email Address Format: Always verify that the recipient’s email address is correctly formatted.