Published on 2019-09-18· Updated on 2022-08-16
The author voluntarily contributed this tutorial as a part of Pepipost Write to Contribute program.
Sending Email is the most common and necessary requirement for most of the applications. Java provides Java Mail API - a platform and protocol independent framework to build mail and messaging applications.
The JavaMail reference implementation is licensed under the Common Development and Distribution License (CDDL) v1.1 and GNU General Public License (GPL) v2 with Classpath Exception.
In this guide, you will get detailed steps on how to setup JavaMail in your Java Project and implement JavaMail API to build and send emails on SMTP protocol.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SendEmail</groupId> <artifactId>SendEmail</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SendEmail</name> <description>This artiface will send emails using Java Mail API</description> </project>
<dependencies> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency> </dependencies>
This will add javax.mail.jar 1.6.2 into your project resources.
Final pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SendEmail</groupId> <artifactId>SendEmail</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SendEmail</name> <description>This artiface will send emails using Java Mail API</description> <dependencies> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency> </dependencies> </project>
In your code, we would require to import the following packages and class.
Below is the full Java code to send emails using Gmail SMTP server, with the description of each line:
package com.sendemail; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMail { public static void main(String[] args) { // Recipient's email ID needs to be mentioned. String to = "[email protected]"; // Sender's email ID needs to be mentioned String from = "[email protected]"; // Assuming you are sending email from through gmails smtp String host = "smtp.gmail.com"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.put("mail.smtp.host", host); properties.put("mail.smtp.port", "465"); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.auth", "true"); // Get the Session object.// and pass username and password Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("[email protected]", "*******"); } }); // Used to debug SMTP issues session.setDebug(true); 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("This is the Subject Line!"); // Now set the actual message message.setText("This is actual message"); System.out.println("sending..."); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } } }
If you want to send HTML content to replace message.setText("This is actual message") with below code:
// Send the actual HTML message. message.setContent( "<h1>This is actual message embedded in HTML tags</h1>", "text/html");
Run Java Application and email will be sent to the recipient. Your console will look like this.
You have successfully sent email using your Java Code.
Now let's send file attachment in your email.
To send a mail with an attachment will have to import a few more classes.
1. import java.io.File and import java.io.IOException
File Class is an abstract representation of file and directory path names and IOException class is a general class of exceptions produced by failed or interrupted I/O operations.
2. import javax.mail.internet.MimeMultipart
This Class is an implementation of the abstract Multipart class that uses MIME conventions for data.
3. import javax.mail.internet.MimeBodyPart
This class represents a MIME body part.
MimeBodyPart uses the InternetHeaders class to parse and store the headers of that body part.
Below is the java code to send an attachment in the email.
The code has two MIME Body part one carrying attachment and other carrying text for email, this is added in Multipart, then this multipart is used to set as the content of the message.
Multipart multipart = new MimeMultipart(); MimeBodyPart attachmentPart = new MimeBodyPart(); MimeBodyPart textPart = new MimeBodyPart(); try { File f =new File("H:\\fakepath\\file1.PNG"); attachmentPart.attachFile(f); textPart.setText("This is text"); multipart.addBodyPart(textPart); multipart.addBodyPart(attachmentPart); } catch (IOException e) { e.printStackTrace(); } message.setContent(multipart);
Here is a running Java Code to send attachments in email:
package com.sendemail; import java.io.File; import java.io.IOException; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class SendMail { public static void main(String[] args) { // Recipient's email ID needs to be mentioned. String to = "[email protected]"; // Sender's email ID needs to be mentioned String from = "[email protected]"; // Assuming you are sending email from through gmails smtp String host = "smtp.gmail.com"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.put("mail.smtp.host", host); properties.put("mail.smtp.port", "465"); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.auth", "true"); // Get the Session object.// and pass Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("[email protected]", "*******"); } }); //session.setDebug(true); 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("This is the Subject Line!"); Multipart multipart = new MimeMultipart(); MimeBodyPart attachmentPart = new MimeBodyPart(); MimeBodyPart textPart = new MimeBodyPart(); try { File f =new File("H:\\pepipost_tutorials\\javaemail1.PNG"); attachmentPart.attachFile(f); textPart.setText("This is text"); multipart.addBodyPart(textPart); multipart.addBodyPart(attachmentPart); } catch (IOException e) { e.printStackTrace(); } message.setContent(multipart); System.out.println("sending..."); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } } }
Now you have implemented Java Mail API successfully and can send emails using any SMTP Servers from your project.
Netcorecloud's toolkit is the solution to all your email problems.
Netcore connects & unifies your data across all sources, connects to your marketing channels and provides you with control over AI Powered automation and personalization.
Rishabh Mishra
Programming Guy! Your coding problem corresponder.