Pages

Thursday, July 23, 2009

Bulk mailing with Bulk attachment

Hi i think - sending bulk mails with bulk attachments problem- is faced by every java programmer in real time projects, I got small solution from my friend, i thought this will be help full for some one who needs the solution for this problem.

please copy and paste the following java code in your mail handler action class,

Note: 1) Multiple Emails are taking with comma[,] seperated.
2) If attachments are more then also we can send mails -- Need to get attachment paths with comma[,] separated.
3) To work with the following code please import javax.mail.*, javax.mail.internet.*, javax.activation.DataHandler, javax.activation.FileDataSource packages.


Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
javax.mail.Session session = Session.getDefaultInstance(props, null);
session.setDebug(sessionDebug);


MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromMailId));
InternetAddress[] address = {new InternetAddress(spiltEmail[i].trim())};
message.setRecipients(Message.RecipientType.TO, address);
message.setSubject(acknowledgementSubject);

message.setText(acknowledgementContent);
message.setSentDate(new Date());
Multipart multiPart = new MimeMultipart();

MimeBodyPart con = new MimeBodyPart();
con.setText(acknowledgementContent);
multiPart.addBodyPart(con);

// Take the below code for multiple attachments also
// Need to copy the same code and change the path to new attachment path

MimeBodyPart bodyPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(path);
bodyPart.setDataHandler(new DataHandler(fds));
bodyPart.setFileName(fds.getName());
//mbp.setText(acknowledgementContent);

multiPart.addBodyPart(bodyPart);
message.setContent(multiPart);

Transport.send(message); //to send the mail successfully

No comments:

Post a Comment