Sending email with attachment useful snippets :
Note: File is used to attach. If you are using nodeRef then you need to read those content and write to some file.
we are using <org.springframework.mail.javamail.JavaMailSender>
we are using <org.springframework.mail.javamail.JavaMailSender>
public void sendEmailWithAttachmentToListUsers(String from, List<String> emails, String subject, String body, String report_name, File fileObj) { try { MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true); helper.setSubject(subject); helper.setText(body,true); helper.setFrom(new InternetAddress(from)); helper.setTo(getAddresses(emails)); //add attachment FileSystemResource file = new FileSystemResource(fileObj.getAbsolutePath()); helper.addAttachment(report_name + ".zip", file); mailSender.send(mimeMessage); logger.debug("## Email sent to -> "+ emails); } catch(MessagingException me) { logger.error(me); } }
//Method getAddresses
private static InternetAddress[] getAddresses(List<String> emailIds) { InternetAddress[] toAddresses = new InternetAddress[emailIds.size()]; try { for(int i=0; i<emailIds.size();i++ ) { toAddresses[i] = new InternetAddress(emailIds.get(i)); } } catch(AddressException ae) { logger.error(ae); } return toAddresses; }
No comments:
Post a Comment