How To Send Email In Java

By bhagwatchouhan
How To Send Email In Java

Email is one of the most important factors in having effective business communication. One can also use emails to host marketing campaigns to reach the appropriate audience. Apart from these uses, there are several other benefits of using email as the communication channel including keeping a record of all the messages.

In this tutorial, we will discuss the parameters involved in sending an email and the possible ways to send an email using Java.

Since the most recent versions of Java have excluded javax package, we need to add the Jar externally as the project dependency to add the javax.mail package. This tutorial provides the required steps for both Maven and Gradle based projects. In case your project is not using Maven or Gradle, you can simply search and download the jar and include it in your project path.

 

Basics of Email

This section explains the basics of sending an email by explaining the parameters involved in an email. We can include the below-listed parameters while sending an email.

From - The mandatory field to specify the sender email address. It must be a valid email address to send an email.

Reply-To - It's an optional parameter to ccept email replies. If not specified, the From email address will be used to send replies.

To - It's the most important and mandatory parameter to send an email. We can include either single or multiple receiver email addresses to send an email either to single or multiple receivers.

// To - Format - RFC 2822 - Single Receipient
Receipient Name <Receipient Email>
// OR
Receipient Email
// To - Format - RFC 2822 - Multiple Receipient
Receipient 1 Name <Receipient 1 Email>, Receipient 2 Name <Receipient 2 Email>
, Receipient 3 Name <Receipient 3 Email>
// OR
Receipient 1 Email, Receipient 2 Email
// OR
Receipient 1 Name <Receipient 1 Email>, Receipient 2 Email

Cc - Carbon Copy - Similar to To, we can specify either single or multiple recipients to receive a copy of the email to keep them notified about the communication.

Bcc - Blank Carbon Copy - We can also involve recipients who will receive a copy of the email without mentioning them to the recipients involved in both To and CC list. The recipients involved in both To and CC list will never know that the same email is also sent to the recipients mentioned in the BCC parameter.

Subject - Though it's not a mandatory field, one must include the subject in order to hint the recipients about the content involved in the email. A short and descriptive subject can tell the recipient about the communication context.

The subject can be of multiple lines separated with a CRLF (\r\n). Each line must not have more than 70 characters.

Message - The actual message to be sent to the recipients mentioned in To, CC, and BCC parameters. Though we can send an email without a message, it's not a preferred way to send an email.

 

Jar Dependency

You can download the Jar for javax.mail and add it as a project dependency in case you are not using Maven or Gradle build systems. Click Here to download the Jar.

 

Maven Dependency

If you are using Maven as the dependency management for your project, you can include the Maven Artifact to your pom.xml as shown below.

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.2</version>
</dependency>

Your pom.xml should be similar to the one as shown below.

<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>JavaEmail</groupId>
  <artifactId>JavaEmail</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <release>12</release>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  	<dependency>
  		<groupId>com.sun.mail</groupId>
  		<artifactId>javax.mail</artifactId>
  		<version>1.6.2</version>
  	</dependency>
  </dependencies>
</project>

Below mentioned is the screenshot of Eclipse to add the dependency to your project.

Java Email POM

Fig 1

 

Gradle Dependency

If you are using Gradle as the dependency management for your project, you can include the Gradle Artifact to your build.gradle as shown below. In Eclipse, you can install Buildship Gradle Integration Plugin to add Gradle support. The most recent versions of Eclipse ships with this plugin.

// https://mvnrepository.com/artifact/com.sun.mail/javax.mail
compile group: 'com.sun.mail', name: 'javax.mail', version: '1.6.2'

Standard Services Configuration

You can also use the standard email services including Gmail, Yahoo, and Outlook to send an email. Below listed are the configurations required to send emails using your Gmail, Yahoo, or Outlook as mentioned below.

; Gmail configurations
Host - smtp.gmail.com
; You can also specify port 587
Port - 465
Username - <Gmail username>
Password - <Gmail password>

; Yahoo configurations
Host - smtp.mail.yahoo.com
Port - 465
Username - <Yahoo username>
Password - <Yahoo password>
; Outlook configurations Host - smtp.live.com Port - 465 Username - <Outlook username> Password - <Outlook password>

You must take special care while sending emails using free accounts since there are limitations in sending emails using these services. These services might block your account in case you exceed the specified limit, hence avoid using personal email accounts.

Gmail limits to a maximum of 100 recipients at a time with a limit of 500 messages per day. Similarly, Yahoo also applies a limit of 100 recipients and 500 messages per day.

You might also need to keep the 2-step verification off if you’re using it.

 

Trigger Email

I have used the Gmail SMTP server for demonstration purposes. You can also use your Email server or any other service provider by providing the proper values of Host, Port, Username, and Password to securely send emails over the port 587. The complete code to trigger an email is shown below.

package com.share.email;
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 EmailUtility {
private String host;
private int port;
private boolean debug; private String username; private String password;
private String senderEmail;
public EmailUtility() {
host = "tls://smtp.gmail.com";
port = 587;
debug = true;
username = "username@gmail.com";
password = "password";
senderEmail = "username@gmail.com"; }
public EmailUtility( String host, int port, String username, String password, String senderEmail ) {
this.host = host;
this.port = port;
this.debug = true;
this.username = username;
this.password = password;
this.senderEmail = senderEmail; }
public void sendMail( String to, String subject, String content ) {
// Set Properties
Properties props = new Properties();
props.put( "mail.smtp.auth", "true" );
props.put( "mail.smtp.host", host );
props.put( "mail.smtp.port", port );
props.put( "mail.smtp.starttls.enable", "true" );
props.put( "mail.debug", debug );
props.put( "mail.smtp.socketFactory.port", port ); //props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory"); props.put( "mail.smtp.socketFactory.fallback", "false" ); props.put( "mail.smtp.ssl.trust", host );
// Create the Session Object
Session session = Session.getDefaultInstance(
props,
new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( username, password ); } } );
try {
MimeMessage message = new MimeMessage( session );
// From
message.setFrom( new InternetAddress( senderEmail ) );
// Reply To
message.setReplyTo( InternetAddress.parse( senderEmail ) );
// Recipient
message.addRecipient( Message.RecipientType.TO, new InternetAddress( to ) );
// Subject
message.setSubject( subject );
// Content
message.setContent( content, "text/html; charset=utf-8" );
Transport.send( message );
}
catch( MessagingException exc ) {
throw new RuntimeException( exc );
}
}
public static void main( String[] args ) {
EmailUtility emailUtility = new EmailUtility();
emailUtility.sendMail( "recipient@gmail.com", "Hello Member", "Thanks for joining us." ); } }

 

Send Email With Attachment

We can also send the emails with the attachment as shown below. We can achieve it by dividing the body into multiple parts using the classes MimeBodyPart and Multipart.

....
....
// Subject
message.setSubject( subject );
// Content MimeBodyPart contentPart = new MimeBodyPart();
contentPart.setText( content, "utf-8", "html" );
// Attachment MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource( "path/to/file" );
attachmentPart.setDataHandler( new DataHandler( fileDataSource ) );
attachmentPart.setFileName( fileDataSource.getName() );
Multipart multipart = new MimeMultipart();
multipart.addBodyPart( contentPart );
multipart.addBodyPart( attachmentPart );
// Content
message.setContent( multipart );
Transport.send( message );
....
....

 

Summary

In this tutorial, we have discussed configuring the Project to add support to the javax.mail package. The last section demonstrated the code required to send emails using Java with and without attachment.

Share this blog:

Profile picture for user bhagwatchouhan
bhagwatchouhan