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.MessagingException;import javax.mail.Multipart;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;
public static void getUtilityWithAttachemnt(String to, String cc, String from, String subject, String text,
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
String host = "SMTP.HOST.COM";
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "25");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
if (to.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
if (cc.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
else
message.setRecipient(Message.RecipientType.CC, new InternetAddress(cc));
// Set Subject: header field
message.setSubject(subject);
// Create the message part
// Create a multipart message
Multipart multipart = new MimeMultipart();
// Set HTML message part
final MimeBodyPart htmlBodyPart = new MimeBodyPart();
htmlBodyPart.setContent(text, "text/html");
multipart.addBodyPart(htmlBodyPart);
// Part two is attachment
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filepath);
messageBodyPart.setDataHandler(new DataHandler(source));
String[] filename = filepath.split("//");
System.out.print("filename--->" + filename[filename.length - 1]);
messageBodyPart.setFileName(filename[filename.length - 1]);
message.saveChanges();
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
message.saveChanges();
Transport.send(message);
// System.out.println("Sent message successfully....");
} catch (MessagingException e) {
e.printStackTrace();
}
}