Picture this: you build an application that can automatically notify your team every time a new record appears in your database. Sample Java Program to Send Email becomes the linchpin that turns your console app into an interactive notification system.
In our digital age, sending emails programmatically is no longer a luxury—it's a necessity. Whether you’re designing a job scheduler or a reporting tool, a reliable email module saves you time and delivers instant feedback to stakeholders. The good news? Java has a built‑in library that makes this task straightforward.
By the end of this post you’ll grasp the foundations of SMTP communication, learn how to configure credentials securely, and see ready‑to‑paste code for sending plain text, HTML, attachments, and secure mail.
Read also: Sample Java Program To Send Email
Understanding the Basics of Email Sending in Java
To send an email, Java uses the JavaMail API, a set of classes that manage the transport of message data between applications and mail servers. The core of this process relies on defining server properties, authenticating, and then forming a Message object that carries the email’s content. This step is crucial because without accurate server settings, your emails will bounce or never leave the application.
Before writing code, collect the following details from your mail provider:
- SMTP server address (e.g.,
smtp.gmail.com) - Port number (587 for TLS, 465 for SSL)
- Username and password
- Authentication requirement (yes/no)
- Security protocol (STARTTLS, SSL, none)
The table below summarises common SMTP settings for popular email services. Having this reference on hand speeds up your setup process and reduces configuration errors.
| Provider | SMTP Host | Port | Security |
|---|---|---|---|
| Gmail | smtp.gmail.com | 587 (STARTTLS) / 465 (SSL) | STARTTLS/SSL |
| Yahoo | smtp.mail.yahoo.com | 587 (STARTTLS) / 465 (SSL) | STARTTLS/SSL |
| Outlook.com | smtp.office365.com | 587 (STARTTLS) | STARTTLS |
| SendGrid | smtp.sendgrid.net | 587 | STARTTLS |
Sample Java Program to Send Email with Plain Text Body
Below is a concise, vanilla Java example that demonstrates how to send a simple text email. Replace the placeholder values with your own credentials and addresses. This snippet only needs the standard JavaMail libraries.
code: import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SimpleTextEmail {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.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@example.com","password");
}});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("user@example.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recipient@test.com"));
message.setSubject("Test Email");
message.setText("This is a test email sent from Java.");
Transport.send(message);
System.out.println("Email sent successfully!");
} catch (MessagingException e) { e.printStackTrace(); }
}
}
Sample Java Program to Send Email Containing HTML Content
Emails with rich formatting capture attention perfectly. Here’s how to embed HTML within a Java message, turning a plain notification into a visually engaging update.
code: Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("user@example.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recipient@test.com"));
message.setSubject("Monthly Report");
String htmlContent = "
Sales Summary
{{META_INFO}}Q3 revenue: $1,200,000
";message.setContent(htmlContent, "text/html");
Transport.send(message);
Sample Java Program to Send Email with Attachments
Attach files—such as PDFs or CSVs—to your Java‑generated emails to provide detailed data. The following example demonstrates an attachment workflow using Multipart objects.
code: MimeBodyPart msgPart = new MimeBodyPart();
msgPart.setText("Please find the attached report.");
MimeBodyPart filePart = new MimeBodyPart();
filePart.attachFile(new File("report.pdf"));
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(msgPart);
multipart.addBodyPart(filePart);
message.setContent(multipart);
Transport.send(message);
Sample Java Program to Send Email via a Secure SMTP Connection
Security is paramount. This snippet ensures your credentials never travel as plain text by enabling SSL/TLS encryption.
code: props.put("mail.smtp.host","smtp.secureprovider.com");
props.put("mail.smtp.port","465");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.socketFactory.port","465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");
props.put("mail.smtp.ssl.enable","true");
After setting up these properties, the rest of the email flow remains identical to the plain‑text example above.
By now you’re equipped to embed email capabilities into almost any Java application. The key takeaways: always verify SMTP settings, authenticate securely, and choose the right content type for your audience.
Ready to add instant notifications or automated reports to your next project? Copy one of the snippets, adapt it to your environment, and watch your Java application become a powerful communication tool. If you hit a snag, search the JavaMail docs or reach out to our community for help.