In this tutorial, we will learn how to send email using Java. In order to send mail in Java we need to have the JavaMail API dependency added to the class path.
Folder Structure:
-
- Create a new Maven QuickStartProject “JavaEmail” and create a package for our src files “com.javainterviewpoint“
- Now add the following dependency in the 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>com.javainterviewpoint</groupId> <artifactId>JavaEmail</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>JavaEmail</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.0</version> </dependency> </dependencies> </project>
- Create the Java classes SendingEmail.java and SendEmailHTMLTemplate.java under com.javainterviewpoint folder.
Send Email using Java
JavaMail Plain Text
package com.javainterviewpoint; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendingEmail { public static void main(String[] args) { // Receiver's email ID String receiver = "[email protected]"; // Sender's email ID String sender = "[email protected]"; // Sending email from localhost String host = "localhost"; // Port of SMTP String port = "25"; // Getting system properties Properties properties = System.getProperties(); // Setting up the mail server properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.port", port); // Get default session object Session session = Session.getDefaultInstance(properties); try { // Create MimeMessage object MimeMessage message = new MimeMessage(session); // Set the Senders mail to From message.setFrom(new InternetAddress(sender)); // Set the recipients email address message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); // Subject of the email message.setSubject("Java Send Email Example"); // Body of the email message.setText("Welcome to Java Interviewpoint"); // Send email Transport.send(message); System.out.println("Mail sent successfully"); } catch (MessagingException me) { me.printStackTrace(); } } }
- Create variables for sender, receiver, host and port
- Get the properties from the System.getProperties()
Properties properties = System.getProperties();
- Set the “mail.smtp.host” and “mail.smtp.port” to the properties instance using the setProperty() method
properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.port", port);
- Get the Java Mail Session instance passing the properties to the getDefaultInstance() method
Session session = Session.getDefaultInstance(properties);
- Create a new MimeMessage object passing the session
MimeMessage message = new MimeMessage(session);
- In order to set the sender and receivers email address we will be using the InternetAddress class.
- Senders email address is set using the setFrom() method of the MimeMessage class, it takes up the InternetAddress class, we will pass the sender string to its constructor.
message.setFrom(new InternetAddress(sender));
- The recipients email address is passed to the addRecipient() method. The recipient type can be Message.RecipientType.TO, Message.RecipientType.CC or Message.RecipientType.BCC
message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
- Set the subject with setSubject() and set the plaintext body content with setText()
message.setSubject("Java Send Email Example"); message.setText("Welcome to Java Interviewpoint");
- Now call the send() method of the Transport class passing the message (MimeMessage) to send the mail
Transport.send(message);
Output:
Mail sent successfully
Note:
You should be having any SMTP server running, if not you will be getting the below error
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2194)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:726)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
In my case, i am using Apache James SMTP Server
JavaMail – Java HTML Email template
package com.javainterviewpoint; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendEmailHTMLTemplate { public static void main(String[] args) { // Receiver's email ID String receiver = "[email protected]"; // Sender's email ID String sender = "[email protected]"; // Sending email from localhost String host = "localhost"; // Port of SMTP String port = "25"; // Getting system properties Properties properties = System.getProperties(); // Setting up the mail server properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.port", port); // Create default session object Session session = Session.getDefaultInstance(properties); try { // Create MimeMessage object MimeMessage message = new MimeMessage(session); // Set the Senders mail to From message.setFrom(new InternetAddress(sender)); // Set the recipients email address message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); // Subject of the email message.setSubject("Java Send Email Example"); // HTML email template String messageBody = "<h3>Welcome to JavaInterviewPoint!</h3><br>"; messageBody += "<b>Java Mail Template example</b><br>"; // Body of the HTML Email message.setContent(messageBody, "text/html"); // Send email Transport.send(message); System.out.println("Mail sent successfully"); } catch (MessagingException me) { me.printStackTrace(); } } }
Leave a Reply