Example usage for org.springframework.mail.javamail MimeMessageHelper MimeMessageHelper

List of usage examples for org.springframework.mail.javamail MimeMessageHelper MimeMessageHelper

Introduction

In this page you can find the example usage for org.springframework.mail.javamail MimeMessageHelper MimeMessageHelper.

Prototype

public MimeMessageHelper(MimeMessage mimeMessage) 

Source Link

Document

Create a new MimeMessageHelper for the given MimeMessage, assuming a simple text message (no multipart content, i.e.

Usage

From source file:org.alfresco.web.bean.TemplateMailHelperBean.java

/**
 * Send an email notification to the specified User authority
 * /*from   w  w  w. j  a  v a2s  . co m*/
 * @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.beangle.notification.notifiers.mail.AbstractMailNotifier.java

public void deliver(T mailMsg) throws NotificationException {
    MimeMessage mimeMsg = mailSender.createMimeMessage();
    try {/*  ww  w  .  j a va 2  s .c o m*/
        if (null == mailMsg.getSendAt()) {
            mimeMsg.setSentDate(new Date());
        } else {
            mimeMsg.setSentDate(mailMsg.getSendAt());
        }
        MimeMessageHelper messageHelper = null;
        String encoding = StringUtils.substringAfter(mailMsg.getContentType(), "charset=");
        if (StringUtils.isEmpty(encoding)) {
            messageHelper = new MimeMessageHelper(mimeMsg);
        } else {
            messageHelper = new MimeMessageHelper(mimeMsg, encoding);
        }
        messageHelper.setText(buildText(mailMsg), StringUtils.contains(mailMsg.getContentType(), "html"));
        String subject = buildSubject(mailMsg);
        messageHelper.setSubject(subject);
        int recipients = addRecipient(mimeMsg, mailMsg);
        beforeSend(mailMsg, mimeMsg);
        if (recipients > 0) {
            mailSender.send(mimeMsg);
            if (logger.isDebugEnabled()) {
                logger.debug("mail sended from {} to {} with subject {}",
                        new Object[] { from, mailMsg.getRecipients(), subject });
            }
        } else {
            logger.warn("{} without any recipients ,sending aborted!", subject);
        }
    } catch (AddressException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    } catch (MessagingException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    }
    afterSend(mailMsg, mimeMsg);
}

From source file:org.devproof.portal.core.module.email.service.EmailServiceImpl.java

@Override
@Transactional(readOnly = true)//w w  w.  j a  v a2 s. co  m
public void sendEmail(EmailTemplate template, EmailPlaceholderBean placeholder) {
    if (emailDisabled) {
        System.out.println("Sending Email <" + placeholder.getToEmail() + ">: " + template.getSubject());
        return;
    }
    // Create email
    try {
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg);
        if (placeholder.getContactEmail() != null) {
            String from = "";
            if (placeholder.getContactFullname() != null) {
                from += placeholder.getContactFullname();
            } else {
                from += placeholder.getContactEmail();
            }
            from += " <" + placeholder.getContactEmail() + ">";
            helper.setFrom(from);
        } else {
            String from = configurationService.findAsString(EmailConstants.CONF_FROM_EMAIL_NAME);
            from += " <" + configurationService.findAsString(EmailConstants.CONF_FROM_EMAIL_ADDRESS) + ">";
            helper.setFrom(from);
        }
        if (placeholder.getToEmail() != null) {
            String name = placeholder.getToFirstname() != null ? placeholder.getToFirstname() : "";
            name += " " + (placeholder.getToLastname() != null ? placeholder.getToLastname() : "");
            if (StringUtils.isBlank(name)) {
                name = placeholder.getToUsername();
            }
            helper.setTo(name + " <" + placeholder.getToEmail() + ">");
        } else {
            String name = placeholder.getFirstname() != null ? placeholder.getFirstname() : "";
            name += " " + (placeholder.getLastname() != null ? placeholder.getLastname() : "");
            if (StringUtils.isBlank(name)) {
                name = placeholder.getUsername();
            }
            helper.setTo(name + " <" + placeholder.getEmail() + ">");
        }
        helper.setSubject(replace(template.getSubject(), placeholder));
        helper.setText("<html><body>" + replace(template.getContent(), placeholder) + "</body></html>", true);
        javaMailSender.send(msg);
        logger.info("Send email to " + placeholder.getToEmail() + " " + template.getSubject());
    } catch (MailException e) {
        throw new UnhandledException(e);
    } catch (MessagingException e) {
        throw new UnhandledException(e);
    }
}

From source file:org.encuestame.business.service.MailService.java

/**
 * Send Email Invitation.//from   w  w  w . j a  v a2s  . co m
 * @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./*w w w .j av  a2  s  . c  om*/
 * @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./*from   www .j  a v  a 2  s. c  o m*/
 * @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  w w. ja v a  2 s .  co m
 */
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.//ww  w  .  j  av a 2  s  .  com
 * @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}/*  w w  w.  j a  va2 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);
}

From source file:org.encuestame.business.service.MailService.java

/**
 * Send a welcome notification after validate the account.
 * @param user//from   ww  w  .j ava2 s  . c o  m
 * @param user {@link UserAccount}
 */
public void welcomeNotificationAccount(final UserAccount user) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            final String _fullName = user.getCompleteName();
            final StringBuffer salute = new StringBuffer(
                    getMessageProperties("mail.message.default.user.presentation", buildCurrentLocale(), null));
            salute.append(" ");
            salute.append(_fullName);
            user.setCompleteName(salute.toString());
            message.setTo(user.getUserEmail());
            message.setSubject(buildSubject(
                    getMessageProperties("mail.message.welcome.message.subject", buildCurrentLocale(), null)));
            message.setFrom(noEmailResponse);
            Map model = new HashMap();
            getLogo(model);
            model.put("domain", domainDefault);
            model.put("user", user);
            final String[] properties = { EnMePlaceHolderConfigurer.getProperty("mail.message.app.name") };
            model.put("welcomeMessage", getMessageProperties("mail.message.welcome.message.description",
                    buildCurrentLocale(), null));
            model.put("enjoyMessage", getMessageProperties("mail.message.welcome.message.enjoyMessage",
                    buildCurrentLocale(), null));
            getGreetingMessage(model);
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "/org/encuestame/business/mail/templates/welcome-account.vm", model);
            message.setText(text, true);
        }
    };
    send(preparator);
}