Friday, April 4, 2008

How to add HTML content to java mails

It is easy to develop e-mail applications using the Java Mail API. This article will demonstrate how to send a e-mail using your java application and how to add attachments and HTML contents to that mail sent by you.

The following code segment illustrates how to send a basic e-mail in java.



import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

// Send a simple, single part, text/plain e-mail
public class TestEmail {

public static void main(String[] args) {

// mention the relevant email addresses!!!
String to = "theguy@theguy.com";
String from = "chulakar@gmail.com";

// mention the ISP's email server!!!
String smtphost = "mail.usermail.net";
int smtpPort = 25;

// Create properties, get Session
Properties props = new Properties();

// If using static Transport.send(),
// need to specify which host to send it to

props.put("mail.smtp.host", smtphost);
props.put("mail.smtp.port", "" + smtpPort);
Session session = Session.getInstance(props);

try {
// Instantiatee a message
Message msg = new MimeMessage(session);

//Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Test E-Mail through Java");
msg.setSentDate(new Date());

// Set message content

//
msg = attachHTML(msg);
msg.setText("This is a test of sending a plain text e-mail through Java.);

//Send the message
Transport.send(msg);
}
catch (MessagingException e) {

e.printStackTrace();
}
}
}

Then we can add attachments and HTML contents to the context of the e-mail. You can try this by uncommenting the "attachHTML" method and commenting out the "msg.text" part of the above code segment. The "attachHTML" method is given below.

public Message attachHTML (Message msg){

Multipart mp = new MimeMultipart("related");


// the attacharray is the array which contains the file names of the
// attachments to be added

if (attacharray != null &&
attacharray.size()>0){
for(int i=0; i MimeBodyPart p1 = new MimeBodyPart();
DataSource source = new FileDataSource(attacharray.get(i).toString());
p1.setDataHandler(new DataHandler(source));
p1.setFileName("AT"+i);
mp.addBodyPart(p1);

}
}

// now create second part
MimeBodyPart p2 = new MimeBodyPart();


//
now add the HTML content for the e-mail which is constructed as a String
//
and called as the "htmlContent"

p2.setContent(
htmlContent, "text/html");

mp.addBodyPart(p2);


// Set Multipart as the message's content
msg.setContent(mp);
return msg;
}



I think the above code will work for you as it did to me. All the best!!

Happy coding!





No comments: