Monday 22 September 2014

How to Send Email from Java Program Example

Sending Email from Java program is a common requirement. It doesn't matter whether you are working on core Java application, web application or enterprise Java EE application, you may need to send email to alert support personal with errors, or just send email to users on registration, password reset or asking them to confirm their email after registration. There are many such scenarios, where you need ability to send emails from Java program. In mature applications, you already have a module or library dealing with all king of email functionality and issues e.g. ability to send attachments, images, including signatures and other rich text formatting on emails, but if you have to code something from scratch then Java's Mail API is perfect place. In this article, we will learn how to send emails from Java application using mail API ( javax.mail ) . Before writing code, you must know some email basics e.g. you need a SMTP (Simple Mail Transfer Protocol) server. If you are running your Java application inLinux, then you should know that SMTP daemon by default listen on port 25. You can use any mail server to send emails from Java, including public email servers like GMail, Yahoo or any other provider, all you need is their SMTP server details e.g. hostname, port, connection parameters etc. You can also use SSL, TLS to securely connectand send emails, but in this example we have kept it simple and just focusing on minimum logic to send mail from Java application. In further articles, we will learn how to send mail using attachments, how to send HTML formatted email, how to attach images in emails, how to use SSL authentication to connect GMail Server and send emails etc. For now, let's understand this simple example of Java Mail API.


Java Code Example to Send Email

Java Program to Send Email using Mail API
In order to send email from Java program you need Java Mail API and Java Activation Framework (JAF), precisely you need mail-1.4.5.jarsmtp-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 managing dependencies and can include all dependencies there. Once you have these JAR files covered, just follow below steps to create and send text email from Java.
  1. Create Session object by calling Session.getDefaultInstance(properties), where properties contains all important properties e.g. hostname of SMTP server. 
  2. Create MimeMessage object by passing Session obtained in previous steps. we have to set different properties in this object such as recipient email address, subject, email body, attachments etc.
  3. Use javax.mail.Transport to send the email message by calling static method send(email), where email can be MimeMessage.

Number of properties you pass to create session differs based on the type of SMTP server, for example if SMTP server doesn't require any authentication you can create the Session object with just one property e.g. smtp.mail.host, no need to provide port even because it listen on default port 25. On the other hand if you are connecting to a SMTP server which requires TLS or SSL authentication, e.g. GMail's SMTP Host then you will need to provide few more properties e.g. mail.smtp.port=547 for TLS and mail.smtp.port=457 for SSL. Here is a complete Java program which connect to default SMTP Server without authentication and send a text email using Java's 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 e-mail from Java program:

$ javac EmailSender.java
$ java EmailSender
Sent email successfully....

As you can see it's very simple to send mails from Java program. Once you have created MimeMessage object, you need to add recipients which can be TOCC or BCC. After setting recipients we have setup subject and finally email content itself by message.setText().  If you want to send an e-mail to multiple email ids then following methods would be used to specify those recipients:

void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException

You can add peoples into TO field by using Message.RecipientType.TO, in CC by Message.RecipientType.CC and into BCC by Message.RecipientType.BCC.

No comments:

Post a Comment