Mail Send With Attachments

Sample Program To Send Mail from Java

package com.webaging.utils;

import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

* @author Ashwin
public class MailSender {

* @param from
* @param to
* @param subject
* @param message
* @throws Exception
public static void sendMail(String host, String fromAddress,
List toAddresses, String subject, String messageContent,
String[] attachments) throws Exception {
// Create empty properties
try {
Properties props = System.getProperties();
props.put("", host);
Session session = Session.getInstance(props, null);

MimeMessage message = new MimeMessage(session);
InternetAddress from = new InternetAddress(fromAddress);

for (Iterator it = toAddresses.iterator(); it.hasNext();) {
new InternetAddress((String);

Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(messageContent + "

", "text/html");

// add any file attachments to the message
addAtachments(attachments, multipart);

// Now Send the message

} catch (Exception e) {
throw e;


* @param attachments
* @param multipart
* @throws MessagingException
* @throws AddressException
protected static void addAtachments(String[] attachments,
Multipart multipart) throws MessagingException, AddressException {
for (int i = 0; i <= attachments.length - 1; i++) {
String filename = attachments[i];
MimeBodyPart attachmentBodyPart = new MimeBodyPart();

// use a JAF FileDataSource as it does MIME type detection
DataSource source = new FileDataSource(filename);
attachmentBodyPart.setDataHandler(new DataHandler(source));

// assume that the filename you want to send is the same as the
// actual file name - could alter this to remove the file path

// add the attachment



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s