$show=/label

Java Program to Send An Email with Plain Text

SHARE:

A quick guide and Java Program to Send An Email with Plain Text using java mail api and possible exceptions.

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.

COMMENTS

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

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,3,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,21,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,74,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,50,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,12,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,9,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Program to Send An Email with Plain Text
Java Program to Send An Email with Plain Text
A quick guide and Java Program to Send An Email with Plain Text using java mail api and possible exceptions.
https://1.bp.blogspot.com/-JIAFbjpAZgY/Xekp9gqyKxI/AAAAAAAAB_g/Xqo2muUlETUhgUsi3TQB4skhvHLbILUyACLcBGAsYHQ/s400/Java%2BProgram%2Bto%2BSend%2BAn%2BEmail%2Bwith%2BPlain%2BText.png
https://1.bp.blogspot.com/-JIAFbjpAZgY/Xekp9gqyKxI/AAAAAAAAB_g/Xqo2muUlETUhgUsi3TQB4skhvHLbILUyACLcBGAsYHQ/s72-c/Java%2BProgram%2Bto%2BSend%2BAn%2BEmail%2Bwith%2BPlain%2BText.png
JavaProgramTo.com
https://www.javaprogramto.com/2019/12/java-program-send-email.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/12/java-program-send-email.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content