December 18, 2014
Hot Topics:

Use JavaMail to Automate Email Distribution

  • February 19, 2010
  • By Sridhar M S
  • Send Email »
  • More Articles »

Advanced Emails

After reading the previous section, sending emails should seem simple. Now, let's add more advanced features to the application. Don't you need attachments with email? The following code creates just that.

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
import java.io.*;
 
class SendAdvancedEmail
{
    final String emailInfo = "EmailInfo.properties";
    Properties properties = new Properties();
 
    public static void main(String args[])
    {
        SendAdvancedEmail sendAdvancedEmail = new SendAdvancedEmail ();
        sendAdvancedEmail.sendEmail();
    }
 
    private void sendEmail()
    {
       try{
            //This is required to load all the properties
           FileInputStream fileInputStream = new FileInputStream(emailInfo);
           properties.load(fileInputStream);
           fileInputStream.close();
        }catch(IOException ioe)
       {
            //throw IOException of your choice.
            //can end here
       }
        System.out.println("Email properties read successfully.");
 
       String smtpAddress = properties.getProperty("smtpAddress");
       String fromAddress = properties.getProperty("fromAddress");
       String toAddress = properties.getProperty("toAddress");
       String emailSubject = properties.getProperty("emailSubject");
       String emailBody = properties.getProperty("emailBody");
 
       Properties props = new Properties();
        props.put("mail.smtp.host", smtpAddress);
        props.put("mail.from", fromAddress);
       Session session = Session.getInstance(props, null);
 
       try
       {
           MimeMessage mimeMessage = new MimeMessage(session);
           mimeMessage.setRecipients(Message.RecipientType.TO,toAddress);
           mimeMessage.setSentDate(new Date());
           mimeMessage.setSubject(emailSubject);
            //The following is required to add attachments
           MimeMultipart multipart = new MimeMultipart();
           //Creating the text part of the email message
           BodyPart bodyPart = new MimeBodyPart();
            //The type is set to "text/plain"
           bodyPart.setText(emailBody);
           //Creating the attachment part of the email message
           BodyPart attachment = new MimeBodyPart();
           DataSource source = new FileDataSource(emailInfo);
           attachment.setDataHandler(new DataHandler(source));
           attachment.setFileName(emailInfo);
           //attachment.setContent(properties, "text/html");
            //Now combining the email message and the attachment
           multipart.addBodyPart(bodyPart);
           multipart.addBodyPart(attachment);
           //Setting the message with the multipart just created
           mimeMessage.setContent(multipart);
 
           System.out.println("Sending e-mail...");
           Transport.send(mimeMessage);
           System.out.println("e-mail sent.");
       }
        catch(MessagingException me)
       {
           System.out.println("e-mail send failed."+me);
           me.getMessage();
       }
    }
}


The important difference between this code listing and the one for sending email in the previous section is the process of building the message body, which is now capable of adding a file as an attachment. The Multipart class is actually split into two sections, the message part and the attachment. The properties are actually the same as for the previous code listing.

You could use Multipart instead of MimeMultipart, but be aware that Multipart is an abstract class and hence requires you to create an instance of MimeMultipart. It's a similar case with MimeMessage. You can use Message, which also is an abstract class. Understanding all the classes used here will help you familiarize yourself with the mail package.

Covering all the other classes and methods in the JavaMail API is beyond the scope of this article. In fact, the code samples do not completely handle all the email scenarios that can occur. The listings are used only as explanations of how to use the code; you can enhance them with other necessary capabilities. Different applications would need these code fragments integrated in different ways that suit their particular requirements. If you were to build a complete email server and client, for example, you would need to understand all the JavaMail classes and methods in detail.

However, the article has provided enough information for you to experiment with sending and receiving emails. Just remember these important tips:

  • The details in the properties file must be accurate to achieve the desired results.
  • Download the JavaMail and the JavaBeans Activation Framework JARs. Ensure that you have mail.jar and activation.jar in your classpath.
  • As of writing this article, I understand that the JavaMail API is integrated into Java SE 6.

Code Download

  • JavaMail_src.zip

    For Further Reading

  • "jGuru: Fundamentals of the JavaMail API" (from Sun Developer Network)

    About the Author

    Sridhar M S is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.

  • Tags: email, Java SE, JavaMail



    Page 2 of 2



    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

    Rocket Fuel