Friday, July 18, 2008

Sending mail with attachment by JAVA

For this class mail-1.4.jar file will be needed as a library which can be found in this following site
http://www.java2s.com/Code/Jar/wsit/Downloadmail14jar.htm

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail {

public SendEmail() {
}
public static void sendEmail(String host, String from, String to, String subject, String infoMessage) throws Exception {
sendEmailWithAttachment(host, from, to, subject, infoMessage, "n/a");
}
public static void sendEmailWithAttachment(String host, String from, String to, String subject, String infoMessage, String fileAttachment) throws Exception {

// Get system properties
Properties props = System.getProperties();

// Setup mail server
props.put("mail.smtp.host", host);

// Get session
Session session = Session.getInstance(props, null);

// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);

// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();

//fill message
messageBodyPart.setText(infoMessage);

Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);

// Part two is attachment
if(!fileAttachment.equals("n/a")){
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("MarbilReport.pdf");
multipart.addBodyPart(messageBodyPart);
}

// Put parts in message
message.setContent(multipart);

// Send the message
Transport.send( message );
}
}

No comments: