Tuesday, March 25, 2008

Sending Mails through Java With Attachment

Properties properties=System.getProperties();
properties.put("mail.smtp.host",EmailNotificationSettings.smtpHost);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "25");

// Creating instance for the Authenicator class for authentication & Get session
Authenticator auth = new PopupAuthenticator();
mailSession = Session.getDefaultInstance (properties, auth);

/**
* try catch block uses to send the mail.
* contains subject,fromAddress,toAddress,Message
*/
try {
mLog.debug(mClassName+"::"+methodName+":: try{}");

// getting the host connection from the EmailNotificationSettings Class
MimeMessage message = new MimeMessage(mailSession);
Multipart multipart = new MimeMultipart();

message.setSubject(emailsettings.messageSubject);
Address fromAddress = new InternetAddress(emailsettings.fromAddress);
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));
for(int i=0;i message.addRecipient(Message.RecipientType.CC, new InternetAddress(EmailNotificationSettings.ccAddresses[i]));
}
for(int i=0;i message.addRecipient(Message.RecipientType.BCC, new InternetAddress(EmailNotificationSettings.bccAddresses[i]));
}

//
//Attach the file to the message
//
MimeBodyPart multipart_attachment = new MimeBodyPart();
DataSource ds = new FileDataSource(emailsettings.fileName);
multipart_attachment.setDataHandler(new DataHandler(ds));
multipart_attachment.setFileName(emailsettings.fileName);
multipart_attachment.setDisposition(Part.ATTACHMENT);
multipart.addBodyPart(multipart_attachment);

message.setSentDate(emailsettings.createdDate);

//
// Add MessageBody to message
//
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setText("Hello.. \n \t" + emailsettings.messageBody1);
multipart.addBodyPart(bodyPart);
message.setContent(multipart);

Transport.send(message);

mLog.debug("Mail sent Successfully");
sendMail = true;

} catch (AddressException exception) {
exception.printStackTrace();
throw new EJBException("Exception in EmailNotificationBean::::send() ");
}catch(AuthenticationFailedException authenticationFailedException){
mLog.error("Exception in"+mClassName+"::"+methodName+"::"+ authenticationFailedException);
}catch (MessagingException exception) {
exception.printStackTrace();
mLog.error("Exception in"+mClassName+"::"+methodName+"::"+ exception.getMessage());
throw new EJBException("Exception in EmailNotificationBean::::send()");
} catch (Exception exception) {
exception.printStackTrace();
mLog.error("Exception in"+mClassName+"::"+methodName+"::"+exception.getMessage());
throw new EJBException("Exception in EmailNotificationBean::::send()");
}

No comments: