In today’s fast‑moving world, sending an automated email is almost as essential as sending a text. Whether it’s a confirmation reminder, a newsletter, or an emergency alert, developers need a reliable way to programmatically deliver messages. That’s why a Sample Java Code to Send Email becomes a must‑know tool for anyone working in Java. By mastering the simplest patterns, you unlock powerful communication that can scale across teams and customers alike.
Java’s legacy library, JavaMail, has remained a staple for over two decades. Even as new frameworks emerge, many developers still rely on it because it’s light, stable, and fully supported by Oracle. During the past year alone, more than 60 % of enterprise applications that send transactional mail use JavaMail. That figure highlights the library’s trustworthiness—and its continued relevance. In this article, you’ll discover how to write clean, reusable code that can send plain‑text, HTML, and attachment emails with ease.
Read also: Sample Java Code To Send Email
Why Understanding Sample Java Code to Send Email Matters
When a developer writes a Sample Java Code to Send Email, they are essentially learning how to bridge the gap between your application logic and the outside world. In an era where communication speed correlates strongly with customer satisfaction, confusing or unreliable mail flows hurt the brand. The lesson, then, is simple: a small amount of well‑structured code can create a strong foundation for outreach, support, and engagement.
A good send‑email routine saves developers hours of debugging and dramatically reduces help‑desk tickets. By exposing reliability, you empower teams to focus on business logic instead of troubleshooting SMTP quirks.
Below are the concrete steps you’ll need: set up library dependencies, configure SMTP settings, create a message, and finally send it. We’ll sprinkle in some real‑world code examples at the end to cement everything.
Sample Java Code to Send Email with Plain Text
Below is the most basic way to send a plain‑text email. It uses the JavaMail API and an SMTP server (such as Gmail or your own provider). While the code is short, it covers everything a beginner needs.
- Step 1: Add dependency in Maven
pom.xmlor Gradle build script. - Step 2: Define SMTP properties.
- Step 3: Create a session and authenticator.
- Step 4: Build the message.
- Step 5: Send it.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class PlainTextMail {
public static void main(String[] args) {
final String username = "your_email@example.com";
final String password = "your_password";
// 1. Set up the SMTP server.
Properties prop = new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.host", "smtp.example.com");
prop.put("mail.smtp.port", "587");
// 2. Create session with authenticator.
Session session = Session.getInstance(prop, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 3. Build the email.
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(
Message.RecipientType.TO, InternetAddress.parse("recipient@example.com"));
message.setSubject("Hello from Java");
// 4. Set the text content.
message.setText("This is a plain‑text email sent from Java.");
// 5. Send.
Transport.send(message);
System.out.println("Email sent successfully!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Sample Java Code to Send Email with HTML Content
For modern marketing or notification mails, HTML formatting adds visual appeal and proper layout. The following example builds upon the plain‑text snippet but replaces the body with rich HTML and styles.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class HtmlMail {
public static void main(String[] args) {
final String username = "your_email@example.com";
final String password = "your_password";
Properties prop = new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.host", "smtp.example.com");
prop.put("mail.smtp.port", "587");
Session session = Session.getInstance(prop, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(
Message.RecipientType.TO, InternetAddress.parse("recipient@example.com"));
message.setSubject("Get Ready for Our New Features!");
String htmlBody = """
Hi there!
{{META_INFO}}
We’re excited to share our newest updates.
Thank you for staying with us.
""";
// Wrap into a MimeBodyPart
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(htmlBody, "text/html; charset=utf-8");
// Set up the multipart
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
// 4. Attach the image (optional)
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.attachFile("/path/to/image.png");
imagePart.setContentID("");
multipart.addBodyPart(imagePart);
// 5. Set content of message
message.setContent(multipart);
// 6. Send
Transport.send(message);
System.out.println("HTML email sent!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sample Java Code to Send Email with Attachments
Sending documents—such as invoices, reports, or images—is commonplace in business applications. The example below shows how to attach a PDF while keeping the email body in plain text.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class AttachmentMail {
public static void main(String[] args) {
final String username = "your_email@example.com";
final String password = "your_password";
Properties prop = new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.host", "smtp.example.com");
prop.put("mail.smtp.port", "587");
Session session = Session.getInstance(prop, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(
Message.RecipientType.TO, InternetAddress.parse("client@example.com"));
message.setSubject("Your Invoice #12345");
// Body part for the message text
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("Dear customer, please find attached your invoice.");
// Attach the PDF
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile("/path/to/invoice12345.pdf");
attachmentPart.setFileName("invoice12345.pdf");
// Combine parts
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(textPart);
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Attachment email sent!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sample Java Code to Send Email Using TLS/SSL and Authentication
Security is crucial. Many SMTP servers now require TLS or SSL. Below is a concise example that enables TLS, uses authentication, and configures the session for a secure connection.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SecureMail {
public static void main(String[] args) {
final String username = "your_email@example.com";
final String password = "your_password";
Properties prop = new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true"); // Enable TLS
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587"); // 587 for TLS
Session session = Session.getInstance(prop, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(
Message.RecipientType.TO, InternetAddress.parse("friend@example.com"));
message.setSubject("Secure Example");
message.setText("This mail uses TLS for a secure channel.");
Transport.send(message);
System.out.println("Secure email sent!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
By following these patterns, you can start crafting robust email integrations for small scripts, enterprise services, or web applications. All the examples above share the same structure, making it easy to swap in different content or add extra attachments whenever needed.
Ready to enrich your app’s communication? Grab the code snippets above, adjust the SMTP details to match your provider, and run them in a sandbox environment. From there, you’ll see how simple it is to scale to thousands of recipients or embed the logic into a service‑oriented architecture. If you’d like to dive deeper into JavaMail, consider exploring the official JavaMail API documentation for advanced features such as message priorities, CC/BCC, and read‑receipt tracking. Happy emailing, and let your Java applications speak louder than words!