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("mail.pop3.host", host);
Session session = Session.getInstance(props, null);

MimeMessage message = new MimeMessage(session);
InternetAddress from = new InternetAddress(fromAddress);
message.setFrom(from);
message.setSubject(subject);

for (Iterator it = toAddresses.iterator(); it.hasNext();) {
message.addRecipient(Message.RecipientType.TO,
new InternetAddress((String) it.next()));
}

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

", "text/html");
multipart.addBodyPart(messageBodyPart);

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

message.setContent(multipart);
// Now Send the message
Transport.send(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
attachmentBodyPart.setFileName(filename);

// add the attachment
multipart.addBodyPart(attachmentBodyPart);
}
}

}

Advertisements