February 27, 2021
Hot Topics:

Use JavaMail to Automate Email Distribution

  • 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 ();
    private void sendEmail()
            //This is required to load all the properties
           FileInputStream fileInputStream = new FileInputStream(emailInfo);
        }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);
           MimeMessage mimeMessage = new MimeMessage(session);
           mimeMessage.setSentDate(new Date());
            //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"
           //Creating the attachment part of the email message
           BodyPart attachment = new MimeBodyPart();
           DataSource source = new FileDataSource(emailInfo);
           attachment.setDataHandler(new DataHandler(source));
           //attachment.setContent(properties, "text/html");
            //Now combining the email message and the attachment
           //Setting the message with the multipart just created
           System.out.println("Sending e-mail...");
           System.out.println("e-mail sent.");
        catch(MessagingException me)
           System.out.println("e-mail send failed."+me);

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.

  • Page 2 of 2

    This article was originally published on February 19, 2010

    Enterprise Development Update

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

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