Monday, 13 September 2010

Sending email using java APIs

Required Jars:
1. mail.jar
2. activation.jar
3. commons-logging-1.0.4.jar

Before testing this method tokens (in blude color) must be replaced with required values. Name of token itself tells what value need to be replaced.

Example:
public static void sendEmail(String sub, String msgBody) {
/**
* Method used to send the email.
 * @param sub
* @param msgBody
* @throws Exception
*/

public static void sendEmail(String sub, String msgBody) {
RecipientType TO = javax.mail.Message.RecipientType.TO;
RecipientType CC = javax.mail.Message.RecipientType.CC;

Properties emailSessionProps = new Properties();

String smtpServerAdd =
emailSessionProps.put(SMTPSERVERPROP, smtpServerAdd);

Session session = null;
session = Session.getInstance(emailSessionProps, null);
session.setDebug(false);

// Create a MimeMessage
Message msg = new MimeMessage(session);

Address addr = null;
try {
// Get email ids (From)

addr = new InternetAddress();

msg.setFrom(addr);

// Get email ids (TO)
StringTokenizer tokenizer = new StringTokenizer(, ";");

ArrayList recipients = new ArrayList();

while (tokenizer.hasMoreTokens()) {

recipients.add(new InternetAddress(tokenizer.nextToken()));

}

Address[] recipientsArray = (InternetAddress[]) recipients
.toArray(new InternetAddress[0]);

// Add the address to the message header
msg.addRecipients(TO, recipientsArray);

// Get email ids (CC) if(cc != null && cc.length() > 0){

StringTokenizer ccTokenizer = new StringTokenizer(, ";");

ArrayList recipientsCC = new ArrayList();

while (ccTokenizer.hasMoreTokens()) {

recipientsCC.add(new InternetAddress(ccTokenizer.nextToken()));
}

Address[] recipientsCcArray = (InternetAddress[]) recipientsCC
.toArray(new InternetAddress[0]);

// Add the address to the message header
msg.addRecipients(CC, recipientsCcArray);

msg.setSubject(sub);

MimeMultipart mimeMultipart = new MimeMultipart();

MimeBodyPart bodyPart = null;

if (msgBody != null) {
bodyPart = new MimeBodyPart();

// Should each of the exceptions be caught separately
// Set message inline text first if any
bodyPart.setContent(msgBody.toString(), "text/html");
bodyPart.setDisposition("INLINE");
mimeMultipart.addBodyPart(bodyPart);
}

msg.setContent(mimeMultipart);

msg.setSentDate(new java.util.Date());

Transport.send(msg);

} catch (MessagingException mex) {

mex.printStackTrace();

}

}