Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Thursday, December 5, 2019

Java Program to Send An Email with Plain Text

1. Overview

In this email sending programming series, You will be learning today how to send an email to a specified email address from a default mail address. Content can be anything in the email. Basically, sending emails is a very common feature in the IT industry. After performing a successful case completion or if an error occurred an email should be triggered. And also summarizing the stats for the day and triggering the email at the end of the day. Any scenario is good choice to send an email. It is absolutely based on the need.

Mostly in all banking companies will be running thousands of control-m jobs that need a notification after completion of each job. control-m triggers a shell script or java code and executes all business logic and in the end, it will send the status of the job in the email. If it is not sending the job status to the right person then no action is taken if the job is failed.

Java Program to Send An Email with Plain Text




2. What are the prerequisites to send an email


Java has provided two API's which are mandatory to send an email. These two libraries should be in classpath. The following are needed.

A) Java Mail API
B) Java Activation Framework
C) Email Server(SMTP) information


JavaMail API is available in the form of mail.jar, Java Activation Framework (JAF) is as activation.jar.

Download the jar files from oracle.com website mail.jar and activation.jar

Maven dependency:


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

And also you should know the mail server information such as host and port. Most of the cases port is optional.

3. Java Program to Send An Email with Plain Text


Let us write a program to send an email with plain text without any attachment.

In the below example code, we are assuming and using the email host as localhost which has the capabilities to trigger an email.

We need to do the following steps.

A) First create the session using Session.getDefaultInstance() method.
B) Create MimeMessage from the session created in the above step.
C) Set all the values to mimemessage such as send email, receiver email, subject, email content, etc.
D) Finally, Send the mime message using Transport.send() method.


package com.javaprogramto.engineering.programs;

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;

/**
 * 
 * Java Program to Send An Email with Plain Text
 * 
 * @author javaprogramto.com venkatesh
 *
 */
public class SendEmailPlainTextExample {

    public static void main(String[] args) {
        // Recipient's email ID storing in string.
        String to = "receipient.email@gmail.com";

        // Sender's email ID storing in String
        String from = "sender.email@gmail.com";

        // Assuming email host as localhost
        String host = "localhost";

        // Get system properties
        Properties properties = System.getProperties();

        // Adding the email host to the system properties.
        properties.setProperty("mail.smtp.host", host);

        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);

        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 which appears in the inbox");

            // Send the actual body or content of email.
            message.setContent(
                    "Dear Customer, You are receiving this email because you are the prime member in our bank. please reach out to us for any information on your accounts.",
                    "text/html");

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");

        } catch (MessagingException mex) {
            mex.printStackTrace();
        }

    }
}

Output:

Before running this program please replace the localhost with the valid SMTP details. Once the email is sent successfully then will print the below message.

Sent message successfully....

If you try to run using localhost then you will be seeing the following runtime exception. Because it is not able to connect to the email server named "localhost".

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
  nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
    at javax.mail.Service.connect(Service.java:291)
    at javax.mail.Service.connect(Service.java:172)
    at javax.mail.Service.connect(Service.java:121)
    at javax.mail.Transport.send0(Transport.java:190)
    at javax.mail.Transport.send(Transport.java:120)
    at com.javaprogramto.engineering.programs.SendEmailPlainTextExample.main(SendEmailPlainTextExample.java:59)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
    ... 7 more

4. Conclusion


In this article, you have learned a basic java code to send the email.

In the next tutorial in the email series, You will learn how to send the email from the Gmail server.

1 comment:

Please do not add any spam links in the comments section.