dcsimg
October 1, 2016
Hot Topics:

Adding Email Support to Your Java Applications

  • January 28, 2015
  • By Manoj Debnath
  • Send Email »
  • More Articles »

Email is an integral part of business communication. Java offers the JavaMail API to make possible email communication from our applications easily. It is a platform- and protocol-independent framework built as a part of the Java EE spectrum of web/enterprise application development. The JavaMail API is a set of abstract classes defining the objects that comprise a mail system. Although mainly targeted towards web/enterprise development, with a few minor adjustments we can add the same benefit of mail and messaging support even to a bare bone, standalone Java application as well.

The Protocol of JavaMail

Protocol literally means maintaining certain norms, code of conduct, and so on. To draw an analogy: If you want to go abroad, protocols you may have to follow are getting a passport, VISA, booking a flight, and so forth. There may be several sub protocols of a protocol, such as how to get a VISA, and the like. The use of protocols in computer networking is analogous. What JavaMail does is provide elements to construct an interface to a messaging system without providing any specific implementation of a protocol. (However, there are classes that implement protocols of RFC 822 and MIME Internet messaging that are delivered with the package; we need not worry.) Creating an application with email support is as simple as any Java programming, but the technical aspects behind the scene are quite intriguing and require some understanding of network protocols. Let's get a very brief idea of protocols supported by the JavaMail API.

  • SMTP (Simple Mail Transfer Protocol) supports the mechanism to deliver email.
  • POP (Post Office Protocol) is the mailbox mechanism we use on the Internet to get mails.
  • IMAP (Internet Message Access Protocol) is an advanced protocol for receiving messages, multiple mailbox support, mailbox sharing, and so forth.
  • MIME (Multipurpose Internet Mail Extension) is the protocol concerned with the content of the message transfer such as message format, attachments, and so on.
  • Others, are some of the protocols provided by a third party to provide features such as S/MIME (Secure/Multipurpose Internet Mail Extension), NNTP (Network News Transfer Protocol), and the like.

Email1
Figure 1: How email moves to its destination

Sending Simple Email

To begin with, to send emails from an Java Application, we need an SMTP server. We can either install an SMTP server or access SMTP servers provided online. Apply one of the following techniques to get one:

  1. Install a SMTP server such as Postfix Server or Apache James Server.
  2. Use a SMTP server provided by A SMTP provider, such as Jango SMTP.
  3. Use a SMTP server provided by companies such as Gmail, Yahoo!, and the like.

The simplest code to send an email through Gmail SMTP is as follows. This is a console application; therefore, the JavaMail API is not included by default. To compile and run this code, you need to add dependencies manually (download JavaMail from here). However, JavaMail is included by default in J2EE, so for a web/enterprise application project it would pose no problem.

package org.mano.mailer;

import java.util.Properties;

import javax.mail.Authenticator;
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 Emailer {
   public static void main(String[] args) {
      Emailer.sendEmail("xyz@gmail.com", "Email test",
         "send from Java App", "abc@gmail.com",
         "user1", "******");
   }

   public static void sendEmail(String to, String subject, String msg,
         String from, String userName, String password) {
      Properties properties = new Properties();
      properties.put("mail.smtp.auth", "true");
      properties.put("mail.smtp.starttls.enable", "true");
      properties.put("mail.smtp.host", "smtp.gmail.com");
      properties.put("mail.smtp.port", "587");
      Session session = Session.getInstance(properties, new Authenticator() {
         protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
          }
      });

      try {
         Message message = new MimeMessage(session);
         message.setFrom(new InternetAddress(from));
         message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(to));
         message.setSubject(subject);
         message.setText(msg);
         Transport.send(message);
         System.out.println("Message send successfully....");
      } catch (MessagingException e) {
         throw new RuntimeException(e);
      }
   }
}

The SMTP server settings are provided through the Properties object, which works as a Map object to map different JavaMail Service properties.

Properties properties = new Properties();

The hostname is set through the mail.smtp.host property. If the host requires authentication, we set the mail.smtp.auth property to a true value. Because we are using the Gmail SMTP server provider, the host and port parameters are as follows. Otherwise, they would change according to the host used.

properties.put("mail.smtp.host",
   "smtp.gmail.com");
properties.put("mail.smtp.port",
   "587");

Once all the properties are set, a session object is instantiated to hold email connection information. The session needs to be authenticated with login information. This authentication is especially required when we are connecting to an SMTP server outside the local area network. The message object represents an actual message and carries all the properties such as to, from, subject, and content. Transport.send() is a static method used finally to send the message.

Email with Attachments

To send an email with an attached file, the following changes have to be made in the preceding code:

import ...
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Emailer {

   public static void main(String[] args) {

      ...//same as above
   }

   public static void sendEmail(String to, String subject, String msg,
         String from, String userName, String password) {
      ...//same as above

      try {
         Message message = new MimeMessage(session);
         message.setFrom(new InternetAddress(from));
         message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(to));
         message.setSubject(subject);

         BodyPart part1=new MimeBodyPart();
         part1.setText(msg);


         File file=new File("/home/mano/temp/Myfile.doc");
         BodyPart part2=new MimeBodyPart();
         DataSource attachment=new FileDataSource(file);
         part2.setDataHandler(new DataHandler(attachment));
         part2.setFileName(file.getName());


         Multipart multiPart=new MimeMultipart();
         multiPart.addBodyPart(part1);
         multiPart.addBodyPart(part2);

         message.setContent(multiPart);

         Transport.send(message);
         System.out.println("Message with attachment
            sent successfully....");
      } catch (MessagingException e) {
         throw new RuntimeException(e);
      }
   }
}

Observe how the message body is segmented into several parts. The first part includes the actual message.

BodyPart part1=new MimeBodyPart();
part1.setText(msg);

The second part includes the attached file from a local disk.

File file=new File("/home/mano/temp/Myfile.doc");
BodyPart part2=new MimeBodyPart();
DataSource attachment=new FileDataSource(file);
part2.setDataHandler(new DataHandler(attachment));
part2.setFileName(file.getName());

Multipart accumulates the parts before sending. Any number of parts can be added to the MimeMultiPart object.

Multipart multiPart=new MimeMultipart();
multiPart.addBodyPart(part1);
multiPart.addBodyPart(part2);

message.setContent(multiPart);

Conclusion

Emailing from Java code is quite crucial on several business applications. JavaMail provides the requisite API that we developers often exploit to get mailed internal exception/error logs of an application from the client. Apart from that, an application having email support is sometimes necessary. JavaMail is powerful and quite able to write an full-fledged email application, such as Outlook Express, with a little effort.


Tags: Java, email, JavaMail, Java EE, API, smtp, POP, imap, MIME, NNTP




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel