List of usage examples for org.springframework.mail.javamail MimeMessagePreparator MimeMessagePreparator
MimeMessagePreparator
From source file:org.alfresco.repo.action.executer.MailActionExecuter.java
public MimeMessageHelper prepareEmail(final Action ruleAction, final NodeRef actionedUponNodeRef, final Pair<String, Locale> recipient, final Pair<InternetAddress, Locale> sender) { // Create the mime mail message. // Hack: using an array here to get around the fact that inner classes aren't closures. // The MimeMessagePreparator.prepare() signature does not allow us to return a value and yet // we can't set a result on a bare, non-final object reference due to Java language restrictions. final MimeMessageHelper[] messageRef = new MimeMessageHelper[1]; MimeMessagePreparator mailPreparer = new MimeMessagePreparator() { @SuppressWarnings("unchecked") public void prepare(MimeMessage mimeMessage) throws MessagingException { if (logger.isDebugEnabled()) { logger.debug(ruleAction.getParameterValues()); }/*from w w w.j a va 2s. co m*/ messageRef[0] = new MimeMessageHelper(mimeMessage); // set header encoding if one has been supplied if (headerEncoding != null && headerEncoding.length() != 0) { mimeMessage.setHeader("Content-Transfer-Encoding", headerEncoding); } // set recipient String to = (String) ruleAction.getParameterValue(PARAM_TO); if (to != null && to.length() != 0) { messageRef[0].setTo(to); // Note: there is no validation on the username to check that it actually is an email address. // TODO Fix this. Serializable ccValue = (String) ruleAction.getParameterValue(PARAM_CC); if (ccValue != null) { if (ccValue instanceof String) { String cc = (String) ccValue; if (cc.length() > 0) { messageRef[0].setCc(cc); } } else if (ccValue instanceof List<?>) { List<String> s = (List<String>) ccValue; messageRef[0].setCc((String[]) s.toArray()); } else if (ccValue.getClass().isArray()) { messageRef[0].setCc((String[]) ccValue); } } Serializable bccValue = (String) ruleAction.getParameterValue(PARAM_BCC); if (bccValue != null) { if (bccValue instanceof String) { String bcc = (String) bccValue; if (bcc.length() > 0) { messageRef[0].setBcc(bcc); } } else if (bccValue instanceof List<?>) { List<String> s = (List<String>) bccValue; messageRef[0].setBcc((String[]) s.toArray()); } else if (bccValue.getClass().isArray()) { messageRef[0].setCc((String[]) bccValue); } } } else { // see if multiple recipients have been supplied - as a list of authorities Serializable authoritiesValue = ruleAction.getParameterValue(PARAM_TO_MANY); List<String> authorities = null; if (authoritiesValue != null) { if (authoritiesValue instanceof String) { authorities = new ArrayList<String>(1); authorities.add((String) authoritiesValue); } else { authorities = (List<String>) authoritiesValue; } } if (authorities != null && authorities.size() != 0) { List<String> recipients = new ArrayList<String>(authorities.size()); if (logger.isTraceEnabled()) { logger.trace(authorities.size() + " recipient(s) for mail"); } for (String authority : authorities) { final AuthorityType authType = AuthorityType.getAuthorityType(authority); if (logger.isTraceEnabled()) { logger.trace(" authority type: " + authType); } if (authType.equals(AuthorityType.USER)) { if (personService.personExists(authority) == true) { NodeRef person = personService.getPerson(authority); if (!personService.isEnabled(authority) && !nodeService.hasAspect(person, ContentModel.ASPECT_ANULLABLE)) { continue; } String address = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL); if (address != null && address.length() != 0 && validateAddress(address)) { if (logger.isTraceEnabled()) { logger.trace("Recipient (person) exists in Alfresco with known email."); } recipients.add(address); } else { if (logger.isTraceEnabled()) { logger.trace( "Recipient (person) exists in Alfresco without known email."); } // If the username looks like an email address, we'll use that. if (validateAddress(authority)) { recipients.add(authority); } } } else { if (logger.isTraceEnabled()) { logger.trace("Recipient does not exist in Alfresco."); } if (validateAddress(authority)) { recipients.add(authority); } } } else if (authType.equals(AuthorityType.GROUP) || authType.equals(AuthorityType.EVERYONE)) { if (logger.isTraceEnabled()) { logger.trace("Recipient is a group..."); } // Notify all members of the group Set<String> users; if (authType.equals(AuthorityType.GROUP)) { users = authorityService.getContainedAuthorities(AuthorityType.USER, authority, false); } else { users = authorityService.getAllAuthorities(AuthorityType.USER); } for (String userAuth : users) { if (personService.personExists(userAuth) == true) { if (!personService.isEnabled(userAuth)) { continue; } NodeRef person = personService.getPerson(userAuth); String address = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL); if (address != null && address.length() != 0) { recipients.add(address); if (logger.isTraceEnabled()) { logger.trace(" Group member email is known."); } } else { if (logger.isTraceEnabled()) { logger.trace(" Group member email not known."); } if (validateAddress(authority)) { recipients.add(userAuth); } } } else { if (logger.isTraceEnabled()) { logger.trace(" Group member person not found"); } if (validateAddress(authority)) { recipients.add(userAuth); } } } } } if (logger.isTraceEnabled()) { logger.trace(recipients.size() + " valid recipient(s)."); } if (recipients.size() > 0) { messageRef[0].setTo(recipients.toArray(new String[recipients.size()])); } else { // All recipients were invalid throw new MailPreparationException("All recipients for the mail action were invalid"); } } else { // No recipients have been specified throw new MailPreparationException("No recipient has been specified for the mail action"); } } // from person - not to be performed for the "admin" or "system" users NodeRef fromPerson = null; final String currentUserName = authService.getCurrentUserName(); final List<String> usersNotToBeUsedInFromField = Arrays.asList(new String[] { AuthenticationUtil.getSystemUserName(), AuthenticationUtil.getGuestUserName() }); if (!usersNotToBeUsedInFromField.contains(currentUserName)) { fromPerson = personService.getPerson(currentUserName); } if (isFromEnabled()) { // Use the FROM parameter in preference to calculating values. String from = (String) ruleAction.getParameterValue(PARAM_FROM); if (from != null && from.length() > 0) { if (logger.isDebugEnabled()) { logger.debug("from specified as a parameter, from:" + from); } // Check whether or not to use a personal name for the email (will be RFC 2047 encoded) String fromPersonalName = (String) ruleAction.getParameterValue(PARAM_FROM_PERSONAL_NAME); if (fromPersonalName != null && fromPersonalName.length() > 0) { try { messageRef[0].setFrom(from, fromPersonalName); } catch (UnsupportedEncodingException error) { // Uses the JVM's default encoding, can never be unsupported. Just in case, revert to simple email messageRef[0].setFrom(from); } } else { messageRef[0].setFrom(from); } } else { // set the from address from the current user String fromActualUser = null; if (fromPerson != null) { fromActualUser = (String) nodeService.getProperty(fromPerson, ContentModel.PROP_EMAIL); } if (fromActualUser != null && fromActualUser.length() != 0) { if (logger.isDebugEnabled()) { logger.debug("looked up email address for :" + fromPerson + " email from " + fromActualUser); } messageRef[0].setFrom(fromActualUser); } else { // from system or user does not have email address messageRef[0].setFrom(fromDefaultAddress); } } } else { if (logger.isDebugEnabled()) { logger.debug("from not enabled - sending from default address:" + fromDefaultAddress); } // from is not enabled. messageRef[0].setFrom(fromDefaultAddress); } // set subject line messageRef[0].setSubject((String) ruleAction.getParameterValue(PARAM_SUBJECT)); if ((testModeRecipient != null) && (testModeRecipient.length() > 0) && (!testModeRecipient.equals("${dev.email.recipient.address}"))) { // If we have an override for the email recipient, we'll send the email to that address instead. // We'll prefix the subject with the original recipient, but leave the email message unchanged in every other way. messageRef[0].setTo(testModeRecipient); String emailRecipient = (String) ruleAction.getParameterValue(PARAM_TO); if (emailRecipient == null) { Object obj = ruleAction.getParameterValue(PARAM_TO_MANY); if (obj != null) { emailRecipient = obj.toString(); } } String recipientPrefixedSubject = "(" + emailRecipient + ") " + (String) ruleAction.getParameterValue(PARAM_SUBJECT); messageRef[0].setSubject(recipientPrefixedSubject); } // See if an email template has been specified String text = null; // templateRef: either a nodeRef or classpath (see ClasspathRepoTemplateLoader) Serializable ref = ruleAction.getParameterValue(PARAM_TEMPLATE); String templateRef = (ref instanceof NodeRef ? ((NodeRef) ref).toString() : (String) ref); if (templateRef != null) { Map<String, Object> suppliedModel = null; if (ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL) != null) { Object m = ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL); if (m instanceof Map) { suppliedModel = (Map<String, Object>) m; } else { logger.warn("Skipping unsupported email template model parameters of type " + m.getClass().getName() + " : " + m.toString()); } } // build the email template model Map<String, Object> model = createEmailTemplateModel(actionedUponNodeRef, suppliedModel, fromPerson); // Determine the locale to use to send the email. Locale locale = recipient.getSecond(); if (locale == null) { locale = (Locale) ruleAction.getParameterValue(PARAM_LOCALE); } if (locale == null) { locale = sender.getSecond(); } // set subject line String subject = (String) ruleAction.getParameterValue(PARAM_SUBJECT); Object subjectParamsObject = ruleAction.getParameterValue(PARAM_SUBJECT_PARAMS); Object[] subjectParams = null; //Javasctipt pass SubjectParams as ArrayList. see MNT-12534 if (subjectParamsObject instanceof List) { subjectParams = ((List<Object>) subjectParamsObject).toArray(); } else if (subjectParamsObject instanceof Object[]) { subjectParams = (Object[]) subjectParamsObject; } else { if (subjectParamsObject != null) { subjectParams = new Object[] { subjectParamsObject.toString() }; } } String localizedSubject = getLocalizedSubject(subject, subjectParams, locale); if (locale == null) { // process the template against the model text = templateService.processTemplate("freemarker", templateRef, model); } else { // process the template against the model text = templateService.processTemplate("freemarker", templateRef, model, locale); } if ((testModeRecipient != null) && (testModeRecipient.length() > 0) && (!testModeRecipient.equals("${dev.email.recipient.address}"))) { // If we have an override for the email recipient, we'll send the email to that address instead. // We'll prefix the subject with the original recipient, but leave the email message unchanged in every other way. messageRef[0].setTo(testModeRecipient); String emailRecipient = recipient.getFirst(); String recipientPrefixedSubject = "(" + emailRecipient + ") " + localizedSubject; messageRef[0].setSubject(recipientPrefixedSubject); } else { messageRef[0].setTo(recipient.getFirst()); messageRef[0].setSubject(localizedSubject); } } // set the text body of the message boolean isHTML = false; if (text == null) { text = (String) ruleAction.getParameterValue(PARAM_TEXT); } if (text != null) { if (isHTML(text)) { isHTML = true; } } else { text = (String) ruleAction.getParameterValue(PARAM_HTML); if (text != null) { // assume HTML isHTML = true; } } if (text != null) { messageRef[0].setText(text, isHTML); } } }; MimeMessage mimeMessage = mailService.createMimeMessage(); try { mailPreparer.prepare(mimeMessage); } catch (Exception e) { // We're forced to catch java.lang.Exception here. Urgh. if (logger.isWarnEnabled()) { logger.warn("Unable to prepare mail message. Skipping.", e); } return null; } return messageRef[0]; }
From source file:org.alfresco.web.bean.TemplateMailHelperBean.java
/** * Send an email notification to the specified User authority * /*from www .j a va2 s .c om*/ * @param person Person node representing the user * @param node Node they are invited too * @param from From text message * @param roleText The role display label for the user invite notification */ public void notifyUser(NodeRef person, NodeRef node, final String from, String roleText) { final String to = (String) this.getNodeService().getProperty(person, ContentModel.PROP_EMAIL); if (to != null && to.length() != 0) { String body = this.body; if (this.usingTemplate != null) { FacesContext fc = FacesContext.getCurrentInstance(); // use template service to format the email NodeRef templateRef = new NodeRef(Repository.getStoreRef(), this.usingTemplate); ServiceRegistry services = Repository.getServiceRegistry(fc); Map<String, Object> model = DefaultModelHelper.buildDefaultModel(services, Application.getCurrentUser(fc), templateRef); model.put("role", roleText); model.put("space", node); // object to allow client urls to be generated in emails model.put("url", new BaseTemplateContentServlet.URLHelper(fc)); model.put("msg", new I18NMessageMethod()); model.put("document", node); if (nodeService.getType(node).equals(ContentModel.TYPE_CONTENT)) { NodeRef parentNodeRef = nodeService.getParentAssocs(node).get(0).getParentRef(); if (parentNodeRef == null) { throw new IllegalArgumentException("Parent folder doesn't exists for node: " + node); } model.put("space", parentNodeRef); } model.put("shareUrl", UrlUtil.getShareUrl(services.getSysAdminParams())); body = services.getTemplateService().processTemplate("freemarker", templateRef.toString(), model); } this.finalBody = body; MimeMessagePreparator mailPreparer = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(to); message.setSubject(subject); message.setText(finalBody, MailActionExecuter.isHTML(finalBody)); message.setFrom(from); } }; if (logger.isDebugEnabled()) logger.debug("Sending notification email to: " + to + "\n...with subject:\n" + subject + "\n...with body:\n" + body); try { // Send the message this.getMailSender().send(mailPreparer); } catch (Throwable e) { // don't stop the action but let admins know email is not getting sent logger.error("Failed to send email to " + to, e); } } }
From source file:org.apache.camel.component.mail.MailProducer.java
public void process(final Exchange exchange) { sender.send(new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { getEndpoint().getBinding().populateMailMessage(getEndpoint(), mimeMessage, exchange); if (LOG.isDebugEnabled()) { LOG.debug("Sending MimeMessage: " + MailUtils.dumpMessage(mimeMessage)); }/*w w w . j a v a 2s . com*/ } }); }
From source file:org.broadleafcommerce.common.email.service.message.MessageCreator.java
public MimeMessagePreparator buildMimeMessagePreparator(final Map<String, Object> props) { MimeMessagePreparator preparator = new MimeMessagePreparator() { @Override// www.j ava2 s . com public void prepare(MimeMessage mimeMessage) throws Exception { EmailTarget emailUser = (EmailTarget) props.get(EmailPropertyType.USER.getType()); EmailInfo info = (EmailInfo) props.get(EmailPropertyType.INFO.getType()); boolean isMultipart = CollectionUtils.isNotEmpty(info.getAttachments()); MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, info.getEncoding()); message.setTo(emailUser.getEmailAddress()); message.setFrom(info.getFromAddress()); message.setSubject(info.getSubject()); if (emailUser.getBCCAddresses() != null && emailUser.getBCCAddresses().length > 0) { message.setBcc(emailUser.getBCCAddresses()); } if (emailUser.getCCAddresses() != null && emailUser.getCCAddresses().length > 0) { message.setCc(emailUser.getCCAddresses()); } String messageBody = info.getMessageBody(); if (messageBody == null) { messageBody = buildMessageBody(info, props); } message.setText(messageBody, true); for (Attachment attachment : info.getAttachments()) { ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getData(), attachment.getMimeType()); message.addAttachment(attachment.getFilename(), dataSource); } } }; return preparator; }
From source file:org.encuestame.business.service.MailService.java
/** * Send Email Invitation.// ww w . j a v a2s . c om * @param email email user * @param username username */ public void sendEmailJoinInvitation(final String email, final String username) { final MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(email); message.setSubject(buildSubject(getMessageProperties("mail.message.join.us.subject"))); message.setFrom(noEmailResponse); @SuppressWarnings("rawtypes") Map model = new HashMap(); getLogo(model); model.put("domain", domainDefault); model.put("username", username); getGreetingMessage(model); final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/org/encuestame/business/mail/templates/invite-enme.vm", "utf-8", model); message.setText(text, true); } }; send(preparator); }
From source file:org.encuestame.business.service.MailService.java
/** * Send Email Invitation./*from ww w . j av a 2s.co m*/ * @param invitation {@link InvitationBean} */ public void sendEmailInvitation(final InvitationBean invitation) { final MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(invitation.getEmail()); message.setSubject(buildSubject(getMessageProperties("email.messages.new.confirmation"))); message.setFrom(noEmailResponse); @SuppressWarnings("rawtypes") Map model = new HashMap(); getLogo(model); model.put("invitation", invitation); model.put("domain", domainDefault); model.put("username", "MyUsername"); model.put("presentationMessage", getMessageProperties("mail.message.default.user.presentation", buildCurrentLocale(), null)); model.put("subscribeMessage", getMessageProperties("mail.message.subscribe", buildCurrentLocale(), null)); model.put("unSubscribeMessage", getMessageProperties("mail.message.unsubscribe", buildCurrentLocale(), null)); getGreetingMessage(model); final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/org/encuestame/business/mail/templates/invitation.vm", "utf-8", model); message.setText(text, true); } }; send(preparator); }
From source file:org.encuestame.business.service.MailService.java
/** * Send email notification./*w w w .j a v a 2s. com*/ * @param notification {@link NotificationBean} * Will by replaced by queued email */ @Deprecated public void sendEmailNotification(final NotificationBean notification) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(notification.getEmail()); message.setSubject(buildSubject("New Password Confirmation")); message.setFrom(noEmailResponse); Map model = new HashMap(); model.put("notification", notification); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/org/encuestame/business/mail/templates/notification.vm", model); message.setText(text, true); } }; send(preparator); }
From source file:org.encuestame.business.service.MailService.java
/** * Sent a email after system startup.// w ww . j a v a 2 s . c om */ public void sendStartUpNotification(final String startupMessage) throws MailSendException { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(EnMePlaceHolderConfigurer.getProperty("setup.email.notification.webmaster")); message.setSubject( buildSubject(getMessageProperties("mail.message.startup", buildCurrentLocale(), null))); message.setFrom(noEmailResponse); final Map model = new HashMap(); model.put("message", startupMessage); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/org/encuestame/business/mail/templates/startup.vm", model); message.setText(text, true); } }; send(preparator); }
From source file:org.encuestame.business.service.MailService.java
/** * Send Password Confirmation Email.//from w w w . j a v a 2 s . co m * @param user */ public void sendPasswordConfirmationEmail(final SignUpBean user) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { final MimeMessageHelper message = new MimeMessageHelper(mimeMessage); log.debug("sendPasswordConfirmationEmail account to " + user.getEmail()); message.setTo(user.getEmail()); message.setSubject(buildSubject(getMessageProperties("email.password.remember.confirmation"))); message.setFrom(noEmailResponse); final Map<String, Object> model = new HashMap<String, Object>(); // build anomymous the salute final String _fullName = user.getUsername(); final StringBuffer salute = new StringBuffer( getMessageProperties("mail.message.default.user.presentation", buildCurrentLocale(), null)); salute.append(" "); salute.append("<b>"); salute.append(_fullName); salute.append("</b>"); user.setFullName(salute.toString()); getLogo(model); model.put("user", user); model.put("password", user.getPassword()); model.put("domain", domainDefault); model.put("passwordMessage", getMessageProperties("mail.message.password.passwordMessage", buildCurrentLocale(), null)); model.put("passwordIntroMessage", getMessageProperties("mail.message.password.passwordIntroMessage", buildCurrentLocale(), null)); model.put("signInMessage", getMessageProperties("mail.message.signInMessage", buildCurrentLocale(), null)); getGreetingMessage(model); // create the template final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/org/encuestame/business/mail/templates/password-confirmation.vm", model); message.setText(text, Boolean.TRUE); } }; send(preparator); }
From source file:org.encuestame.business.service.MailService.java
/** * Sent email to confirm user account by email. * @param user {@link SignUpBean}// www. ja v a 2 s . com * @param inviteCode invite code string. */ public void sendConfirmYourAccountEmail(final SignUpBean user, final String inviteCode) { final MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { final MimeMessageHelper message = new MimeMessageHelper(mimeMessage); log.debug("confirm account to " + user.getEmail()); message.setTo(user.getEmail()); message.setSubject(buildSubject( getMessageProperties("email.message.confirmation.message", buildCurrentLocale(), null))); message.setFrom(noEmailResponse); final Map<String, Object> model = new HashMap<String, Object>(); if (user.getFullName() == null) { // build user.setFullName(getMessageProperties("mail.message.default.user.full.presentation", buildCurrentLocale(), null)); } else { // build anomymous the salute final String _fullName = user.getFullName(); final StringBuffer salute = new StringBuffer(getMessageProperties( "mail.message.default.user.presentation", buildCurrentLocale(), null)); salute.append(" "); salute.append(_fullName); user.setFullName(salute.toString()); } getLogo(model); model.put("user", user); model.put("inviteCode", inviteCode); model.put("domain", domainDefault); model.put("successMessage", getMessageProperties("mail.message.registration.success", buildCurrentLocale(), null)); model.put("confirmMessage", getMessageProperties("mail.message.confirm.please", buildCurrentLocale(), null)); model.put("confirmMessageSubfooter", getMessageProperties("mail.message.confirm.subfooter", buildCurrentLocale(), null)); getGreetingMessage(model); // create the template final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/org/encuestame/business/mail/templates/confirm-your-account.vm", model); message.setText(text, Boolean.TRUE); } }; send(preparator); }