JavaRush /Java Blog /Random EN /How to send an email from a Java application (with exampl...
PodoBulge
Level 31
Минск

How to send an email from a Java application (with example)

Published in the Random EN group
Sending an email from a Java application is a common requirement. It doesn't matter whether you're working on a core Java application, a web application, or an enterprise Java application, you may need to send an email to alert support staff about errors, or simply send an email to users upon registration, reset their password, or ask them to confirm email address after registration. There are many scenarios when you need the ability to send emails from a Java application. How to send an email from a Java application (with example) - 1In ready-made applications you already have a module or library that works with all the features for sending emails, such as the ability to send attachments, images, including signatures and rich text in emails, BUT if you need to write something from scratch, then Java Mail API is a great option. In this article, we will learn how to send emails from a Java application using the mail API ( javax.mail ). Before writing code you should know some basics of how email works, for example you need an SMTP (Simple Mail Transfer Protocol) server . If you are running your Java application on Linux, then you should know that the SMTP daemon uses port 25. You can use any mail server to send messages using Java, including public mail servers such as GMail, Yahoo or any other service provider, all you need is their SMTP server details , such as hostname, port, connection parameters, etc. You can also use SSL ( secure sockets layer ), TLS ( Transport Layer Security ) to securely connect and send emails, but we made this example simple and focused on minimal logic for sending letters from a Java application. In future articles we will learn how to send an email using attachments, how to send an HTML formatted email, how to attach images to an email, how to use SSL authentication to connect to the GMail server and send emails, etc. Now, let's understand (discuss) this simple Java Mail API example .

Example Java code for sending an email

To send a letter from a Java program, you will need the Java Mail API and Java Activation Framework (JAF) ; to be more precise, you will need mail-1.4.5.jar , smtp-1.4.4.jar , and activation-1.1.jar . You need to download these JAR files and include them in your Classpath to run this program. Alternatively, you can use Maven for dependency management and include all dependencies there. Once you have all these JAR files, simply follow the steps below to create and send an email using Java.
  1. Create an object Sessionby calling Session.getDefaultInstance(properties), where properties- contains all the important properties, for example, the host name of the SMTP server.

  2. Create an object MimeMessageby passing it the object Sessionobtained in the previous step. We have a set of different properties in this object such as email recipient, subject, message body, attachments, etc.

  3. Use it javax.mail.Transportto send an email by calling a static method send(email), where email can be an object MimeMessage.

The number of properties you pass to create an object Sessiondiffers depending on the type of SMTP server, for example, if you are using an SMTP server that does not require any authentication, you can create an object Sessionwith only one property, for example, smtp.mail.host, and you no need to specify the port because it has port 25 by default. On the other hand, if you are connecting to an SMTP server that requires TLS or SSL authentication, such as GMail's SMTP Host, then you need to provide a bit more properties, such as mail.smtp.port=547 for TLS and mail.smtp.port= 457 for SSL. This is a complete Java program that connects to a standard SMTP server without authentication and sends a text message using the Java Mail API.

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 text mail using default SMTP server and without authentication. 
* You need mail.jar, smtp.jar and activation.jar to run this program. 
* 
* @author Javin Paul 
*/ 

public class EmailSender{
     public static void main(String args[]){ 

           String to = "receive@abc.om";         // sender email 
           String from = "sender@abc.com";       // receiver email 
           String host = "127.0.0.1";            // mail server host 

           Properties properties = System.getProperties(); 
           properties.setProperty("mail.smtp.host", host); 

           Session session = Session.getDefaultInstance(properties); // default session 
           
           try { 
                MimeMessage message = new MimeMessage(session); // email message 

                message.setFrom(new InternetAddress(from)); // setting header fields  

                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 

                message.setSubject("Test Mail from Java Program"); // subject line 

                // actual mail body   
                message.setText("You can send mail from Java program by using mail API, but you need" +          
                                "couple of more JAR files e.g. smtp.jar and activation.jar"); 
                
                // Send message 
                Transport.send(message); System.out.println("Email Sent successfully...."); 
               } catch (MessagingException mex){ mex.printStackTrace(); } 

     } 

}
Output: You can compile and run this program to send a simple email from a Java program:

$ javac EmailSender.java
$ java EmailSender
Sent email successfully.... As you can see, it is very easy to send emails from a Java program. Once you have created the object MimeMessage, you need to add recipients, which can be specified in the TO, CC, BCC. Having finished with the recipients, we need to specify the subject of the letter, and, finally, the content of the letter itself by calling the method message.setText(); If you want to do multiple mailings, then the following methods can be used to specify recipients:

void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException
You can add people to the field TOusing Message.RecipientType.TO, to the field CCusing Message.RecipientType.CC, and to BCC- Message.RecipientType.BCC.

Errors and Exceptions

When many Java programmers first start writing a program to send an email, they come across an error because most of them think that mail.jar and activation.jar will be enough to send an email from a Java application, which is not the case, especially if you send email through a local SMTP server in Linux. If you run this program with only mail.jar and activation.jar in your CLASSPATH, you will most likely get this error.

Exception 1:


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:1984) 
            at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:656) 
            at javax.mail.Service.connect(Service.java:345) 
            at javax.mail.Service.connect(Service.java:226) 
            at javax.mail.Service.connect(Service.java:175) 
            at javax.mail.Transport.send0(Transport.java:253) 
            at javax.mail.Transport.send(Transport.java:124) 
            at Testing.main(Testing.java:62) 
        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:339) 
            at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) 
            at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) 
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) 
            at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) 
            at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) 
            at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:301) 
            at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:229) 
            at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1950) 
       ... 7 more
Although the solution to this error is very simple, it can confuse you. java.net.ConnectException: Connection refused: connectIt usually crashes when the server is not working or the port you are connecting to is incorrectly specified. Solution: in addition to mail-1.4.5.jar, you also need smtp-1.4.4.jar and activation-1.1.jar.

Exception 2:

This is another error called NoClassDefFoundError, which usually refers to a missing JAR file in Classpath

Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/MessagingException
           at java.lang.Class.getDeclaredMethods0(Native Method) 
           at java.lang.Class.privateGetDeclaredMethods(Class.java:2521) 
           at java.lang.Class.getMethod0(Class.java:2764) 
           at java.lang.Class.getMethod(Class.java:1653) 
           at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494) 
           at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486) 
Caused by: java.lang.ClassNotFoundException: javax.mail.MessagingException 
           at java.net.URLClassLoader$1.run(URLClassLoader.java:366) 
           at java.net.URLClassLoader$1.run(URLClassLoader.java:355) 
           at java.security.AccessController.doPrivileged(Native Method) 
           at java.net.URLClassLoader.findClass(URLClassLoader.java:354) 
           at java.lang.ClassLoader.loadClass(ClassLoader.java:424) 
           at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) 
           at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
Solution: I managed to solve my problem, it was due to an incorrect Classpath. Even though I had all three required JARs, a Java class file for the program in the same directory, and ran the program from there, Java couldn't figure it out. I tried the following commands and the program worked fine:

java -cp mail-1.4.5.jar:smtp-1.4.4.jar:activation-1.1.jar:. JavaMailSender
Sent email successfully.... Please note that the current directory is marked with a dot at the end of the Classpath argument. Since I was running the program on Linux, I used a colon (:) instead of a semicolon (;) (as in Windows). That's all about how to send an email from a Java application using the mail API. You may find this very simple, since you don't need anything more than three JAR files. It's much easier if you use Gradle or Maven to manage dependencies. In the following tutorials we will see more complex examples of the Java Mail API for sending emails with attachments, with pictures, and beautifully formatted emails for sending reports and tables. Translation of the article: How to Send Email from Java Program with Example
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION