Sunday, February 26, 2012

Apache commons mail utility

Following Jar files are required:

1: commons-email-1.2
2: mail.jar (java mail api)

************************************************************************
package apacheCommonsMailUtility;

import java.net.URL;
import java.util.Properties;

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

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;

/**
 * The Class ApacheCommonsMailUtility.
 */
public class ApacheCommonsMailUtility {

/**
* Send simple text email via gmail.
*
* @return true, if successful
*/
public static boolean sendSimpleTextEmailViaGmail(){
boolean mailFlag=false;
try{
System.out.println("Sending email via gmail..");
/*The call to setHostName("mail.myserver.com") sets the address of the outgoing SMTP
     server that will be used to send the message. If this is not set, the system property "mail.host" will be used.
*/
Email sendMail = new SimpleEmail();
sendMail.setHostName("smtp.gmail.com");
sendMail.setSmtpPort(587);// 465 or 587
sendMail.setAuthenticator(new DefaultAuthenticator("xxxxxxxx", "xxxxxxx")); //username & password
sendMail.setTLS(true);
sendMail.setFrom("strutsspringdemo@gmail.com");
sendMail.setSubject("TestMail");
sendMail.setMsg("This is a test mail ... :-)");
sendMail.addTo("abhinavmishra@gmail.com","Abhinav Mishra");
sendMail.addCc("abhinavmishra@gmail.com","Abhinav");
sendMail.addBcc("strutsspringdemo@gmail.com", "Demo");
sendMail.send();
mailFlag=true;
System.out.println("Email sent successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed..");
e.printStackTrace();
}
return mailFlag;
}

/**
* Send simple text email.
*
* @return true, if successful
*/
public static boolean sendSimpleTextEmail(){
boolean mailFlag=false;
try{
System.out.println("Sending email..");
/*The call to setHostName("mail.myserver.com") sets the address of the outgoing SMTP
       server that will be used to send the message. If this is not set, the system property "mail.host" will be used.
*/
Email sendMail= new SimpleEmail();
sendMail.setHostName("10.000.0.00"); //smtp host
sendMail.setSmtpPort(25);
//NOT NEEDED FOR LOCAL ORG MAILS.
//sendMail.setAuthenticator(new DefaultAuthenticator("xxxx","xxxx"));
sendMail.setFrom("demo@demo.com");
sendMail.setSubject("TestMail..");
sendMail.setMsg("This is a test mail ... :-)");
sendMail.addTo("abhinavkumar_mishra@gmail.com","Abhinav Mishra");
sendMail.addCc("abhinavkumar_mishra@gmail.com","Abhinav");
sendMail.addBcc("akm@gmail.com", "Demo");
sendMail.send();
mailFlag=true;
System.out.println("Email sent successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed..");
e.printStackTrace();
}
return mailFlag;
}

/**
* To add attachments to an email, you will need to use the MultiPartEmail class.
* This class works just like SimpleEmail except that it adds several overloaded attach() methods to add attachments to the email.
* You can add an unlimited number of attachments either inline or attached. The attachments will be MIME encoded.
* The simpliest way to add the attachments is by using the EmailAttachment class to reference your attachments.
* In the following example, we will create an attachment for a picture. We will then attach the picture to the email and send it.
*
* @return true, if successful
*/
public static boolean sendEmailWithAttachment(){
boolean mailFlag=false;
try{
System.out.println("Sending email with attachment..");
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("test-Sequence-diagram.png"); //This image should be in root of project
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("test sequence diagram..");
attachment.setName("Sequence diagram.png");

// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName("10.000.0.00"); //smtp host
email.setSmtpPort(25);
email.addTo("abhinavkumar_mishra@gmail.com", "Abhinav mishra");
email.addCc("abhinavkumar_mishra@gmail.com","Abhinav");
email.addBcc("teszt@gmail.com", "Demo");
email.setFrom("demmo@apache.org", "Demo");
email.setSubject("The picture");
email.setMsg("Here is the picture you wanted");

// add the attachment
email.attach(attachment);

// send the email
email.send();
mailFlag=true;
System.out.println("Email sent with attachment successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed with attachment..");
e.printStackTrace();
}
return mailFlag;
}

/**
* You can also use EmailAttachment to reference any valid URL for files that you do not have locally.
* When the message is sent, the file will be downloaded and attached to the message automatically.
*
* @return true, if successful
*/
public static boolean sendEmailWithAttachmentAsUrl(){
boolean mailFlag=false;
try{
System.out.println("Sending email with attachment as url..");
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setURL(new URL("http://www.apache.org/images/asf_logo_wide.gif"));
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Apache logo");
attachment.setName("Apache logo.gif");

// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName("10.00.00.00"); //smtp host
email.setSmtpPort(25);
email.addTo("abhinavkumar_mishra@gmail.com", "Abhinav mishra");
email.addCc("abhinavkumar_mishra@gmail.com","Abhinav");
email.addBcc("test@gmail.com", "Demo");
email.setFrom("demmo@apache.org", "Demo");
email.setSubject("The picture");
email.setMsg("Here is the picture you wanted");

// add the attachment
email.attach(attachment);

// send the email
email.send();
mailFlag=true;
System.out.println("Email sent with attachment successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed with attachment as url..");
e.printStackTrace();
}
return mailFlag;
}

/**
* Sending HTML formatted email is accomplished by using the HtmlEmail class.
* This class works exactly like the MultiPartEmail class with additional methods to set the html content,
* alternative text content if the recipient does not support HTML email, and add inline images.
* First, notice that the call to embed() returns a String.
* This String is a randomly generated identifier that must be used to reference the image in the image tag.
* Next,there was no call to setMsg() in this example.
* The method is still available in HtmlEmail but it should not be used if you will be using inline images.
* Instead, the setHtmlMsg() and setTextMsg() methods were used.
* @return true, if successful
*/
public static boolean sendEmailHtmlFormat(){
boolean mailFlag=false;
try{
System.out.println("Sending email in html format..");
// Create the email message
HtmlEmail email = new HtmlEmail();
email.setHostName("10.000.0.00");
email.setSmtpPort(25);
email.addTo("abhinavkumar_mishra@gmail.com", "Abhinav mishra");
email.addCc("abhinavkumar_mishra@gmail.com","Abhinav");
email.addBcc("test@gmail.com", "Demo");
email.setFrom("demmo@apache.org", "Demo");
email.setSubject("The picture");

// embed the image and get the content id
URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
String cid = email.embed(url, "Apache logo");

// set the html message
email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");

// set the alternative message
email.setTextMsg("Your email client does not support HTML messages");

// send the email
email.send();
mailFlag=true;
System.out.println("Email sent in html format successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed in html format..");
e.printStackTrace();
}
return mailFlag;
}



/**
* Send emailwith embeded image using mail api.
*
* @return true, if successful
*/
public static boolean sendEmailwithEmbededImageUsingMailApi(){
boolean mailFlag=false;
try{
System.out.println("Sending email with embeded image..");
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "10.000.0.00");
props.setProperty("mail.port", "25");
props.setProperty("mail.user", "xxxx");
props.setProperty("mail.password", "xxxx");

Session mailSession = Session.getDefaultInstance(props, null);

mailSession.setDebug(true); //We can enable debugging as true..

Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);
message.setSubject("HTML  mail with images");
message.setFrom(new InternetAddress("abhinav@gmail.com"));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("abhinavkumar_mishra@gmail.com"));
message.addRecipient(Message.RecipientType.CC,
new InternetAddress("abhinavkumar_mishra@gmail.com"));
message.addRecipient(Message.RecipientType.BCC,
new InternetAddress("abhinavkumar_mishra@gmail.com"));

//
// This HTML mail have to 2 part, the BODY and the embedded image
//
MimeMultipart multipart = new MimeMultipart("related");

// first part  (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
messageBodyPart.setContent(htmlText, "text/html");

// add it
multipart.addBodyPart(messageBodyPart);

// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource("CitationSearchModule-Sequence-diagram.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","<image>");

// add it
multipart.addBodyPart(messageBodyPart);

// put everything together
message.setContent(multipart);

transport.connect();
transport.sendMessage(message,message.getAllRecipients());
transport.close();
mailFlag=true;
System.out.println("Email sent with embeded image successfully..");
}catch (Exception e) {
mailFlag=false;
System.out.println("Email sending failed with embeded image..");
e.printStackTrace();
}
return mailFlag;
}
}

No comments:

Post a Comment

Thanks for your comments/Suggestions.