Sample Programs

Sample java program to send an email with attachments

The JavaMail API is not part of core Java SE, but an optional extension. In addition, it is required in Java Enterprise Edition. The JavaMail packages can be accessed in two ways:

  • by placing j2ee.jar in the classpath
  • or, by placing both mail.jar and activation.jar in the classpath

The javax.mail API uses a properties file for reading server names and related configuration. These settings will override any system defaults. Alternatively, the configuration can be set directly in code, using the JavaMail API.

In below example, I am sending mail using JavaMail API with GMail SMTP on Port 465.


package com.jusfortechies.mail;

import java.io.InputStream;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendEmailWithAttachments {
  private static Properties properties = null;

  static {
    // Load the properties file
    try {
      properties = new Properties();
      InputStream inputStream = SendEmail.class.
         getClassLoader().getResourceAsStream("mail.properties");
      properties.load(inputStream);
    } catch (Exception e) {
      // Catching the exception as null condition is handled in the methods.
    }
 }

 public static void sendMultiPartMail(String from, String to, 
   String subject, String text, String[] attachments) throws Exception {
    if (properties.isEmpty()) {
      throw new Exception("Cannot send mail. Host data not available.");
    }

    // Authenticate the session with username and password
    Session session = Session.getInstance(properties, new Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication()
      {
        return new PasswordAuthentication((String)properties.
		    get("mail.login.username"), 
			(String)properties.get("mail.login.password"));
      }
    });

    // Create to and from addresses
    InternetAddress fromAddress = new InternetAddress(from);
    InternetAddress toAddress = new InternetAddress(to);

    // Create the message instance and add the sender, 
	// recipient, subject and body.
    Message msg = new MimeMessage(session);
    msg.setFrom(fromAddress);
    msg.setSubject(subject);
    msg.setRecipient(RecipientType.TO, toAddress);

    Multipart multipart = new MimeMultipart();
    BodyPart part1 = new MimeBodyPart();
    part1.setText(text);
    multipart.addBodyPart(part1);

    BodyPart attachment = null; 
    for (String filename : attachments) {
      attachment = new MimeBodyPart();
      DataSource source = new FileDataSource(filename);
      attachment.setDataHandler(new DataHandler(source));
      attachment.setFileName(filename);
      multipart.addBodyPart(attachment);
    }

    msg.setContent(multipart);

    Transport.send(msg);
  }
}
 

Also you need to set the below properties in a properties file called mail.properties.

# Configuration file for javax.mail 
# If a value for an item is not provided, then 
# system defaults will be used. These items can 
# also be set in code. 

mail.smtp.host=smtp.gmail.com
mail.smtp.auth=true

mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.fallback=false

# This is your login name and password not required. Instead of 
# hardcoding them in program, I have added here.
mail.login.username=abc@xyz.com
mail.login.password=*****

 

You need to download below jars to run the example
1. j2ee.jar
or
1. mail.jar and activation.jar



blog comments powered by Disqus