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

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

Introduction

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

Prototype

public void setSubject(String subject) throws MessagingException 

Source Link

Document

Set the subject of the message, using the correct encoding.

Usage

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

/**
 * Send Password Confirmation Email./*  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}//from   www . jav a2  s.co  m
 * @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  w  w w  .ja v  a 2  s  .c  om
 * @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);
}

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

/**
 * Send Mime Email.//  w  ww . ja va2s  . c o m
 * @param model
 * @param email
 * @param subject
 * @param from
 * @param template
 */
public void sendMimeEmail(final Map model, final String email, final String subject, final String from,
        final String template) {
    final MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(email);
            message.setSubject(buildSubject(subject));
            message.setFrom(from);
            final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model);
            message.setText(text, true);
        }
    };
    this.send(preparator);
}

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

/**
 * Sent a email after system startup./*from   w  w w.j a v a 2s  .c o m*/
 */
public void sendStartUpNotification(final String startupMessage) {
    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.jasig.portal.portlets.account.UserAccountHelper.java

public void sendLoginToken(HttpServletRequest request, ILocalAccountPerson account) {

    IPerson person = personManager.getPerson(request);
    final Locale[] userLocales = localeStore.getUserLocales(person);
    LocaleManager localeManager = new LocaleManager(person, userLocales);
    Locale locale = localeManager.getLocales()[0];

    IPortalUrlBuilder builder = urlProvider.getPortalUrlBuilderByPortletFName(request, "reset-password",
            UrlType.RENDER);/*w  ww.  ja va  2s. co  m*/
    IPortletUrlBuilder portletUrlBuilder = builder.getTargetedPortletUrlBuilder();
    portletUrlBuilder.addParameter("username", account.getName());
    portletUrlBuilder.addParameter("loginToken", (String) account.getAttributeValue("loginToken"));
    portletUrlBuilder.setPortletMode(PortletMode.VIEW);
    portletUrlBuilder.setWindowState(WindowState.MAXIMIZED);

    StringBuffer url = new StringBuffer();
    url.append(request.getScheme());
    url.append("://").append(request.getServerName());
    int port = request.getServerPort();
    if (port != 80 && port != 443) {
        url.append(":").append(port);
    }
    url.append(builder.getUrlString());

    log.debug("Sending password reset instructions to user with url " + url.toString());

    String emailAddress = (String) account.getAttributeValue("mail");

    final STGroup group = new STGroupDir(templateDir, '$', '$');
    final ST template = group.getInstanceOf(passwordResetTemplate);
    template.add("displayName", person.getAttribute("displayName"));
    template.add("url", url.toString());

    MimeMessage message = mailSender.createMimeMessage();
    String body = template.render();

    try {

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(emailAddress);
        helper.setText(body, true);
        helper.setSubject(messageSource.getMessage("reset.your.password", new Object[] {}, locale));
        helper.setFrom(portalEmailAddress, messageSource.getMessage("portal.name", new Object[] {}, locale));

        log.debug("Sending message to " + emailAddress + " from " + Arrays.toString(message.getFrom())
                + " subject " + message.getSubject());
        this.mailSender.send(message);

    } catch (MailException e) {
        log.error("Unable to send password reset email ", e);
    } catch (MessagingException e) {
        log.error("Unable to send password reset email ", e);
    } catch (UnsupportedEncodingException e) {
        log.error("Unable to send password reset email ", e);
    }
}

From source file:org.jasig.ssp.service.impl.MessageServiceImpl.java

@Override
@Transactional(readOnly = false)/*www  .  ja  v  a2s .  c  o m*/
public boolean sendMessage(@NotNull final Message message)
        throws ObjectNotFoundException, SendFailedException, UnsupportedEncodingException {

    LOGGER.info("BEGIN : sendMessage()");
    LOGGER.info(addMessageIdToError(message) + "Sending message: {}", message.toString());

    try {
        final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        final MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);

        // process FROM addresses
        InternetAddress from;
        String appName = configService.getByName("app_title").getValue();

        //We used the configured outbound email address for every outgoing message
        //If a message was initiated by an end user, their name will be attached to the 'from' while
        //the configured outbound address will be the actual address used for example "Amy Aministrator (SSP) <myconfiguredaddress@foobar.com>"
        String name = appName + " Administrator";
        if (message.getSender() != null && !message.getSender().getEmailAddresses().isEmpty()
                && !message.getSender().getId().equals(Person.SYSTEM_ADMINISTRATOR_ID)) {
            InternetAddress[] froms = getEmailAddresses(message.getSender(), "from:", message.getId());
            if (froms.length > 0) {
                name = message.getSender().getFullName() + " (" + appName + ")";
            }
        }

        from = new InternetAddress(configService.getByName("outbound_email_address").getValue(), name);
        if (!this.validateEmail(from.getAddress())) {
            throw new AddressException("Invalid from: email address [" + from.getAddress() + "]");
        }

        mimeMessageHelper.setFrom(from);
        message.setSentFromAddress(from.toString());
        mimeMessageHelper.setReplyTo(from);
        message.setSentReplyToAddress(from.toString());

        // process TO addresses
        InternetAddress[] tos = null;
        if (message.getRecipient() != null && message.getRecipient().hasEmailAddresses()) { // NOPMD by jon.adams         
            tos = getEmailAddresses(message.getRecipient(), "to:", message.getId());
        } else {
            tos = getEmailAddresses(message.getRecipientEmailAddress(), "to:", message.getId());
        }
        if (tos.length > 0) {
            mimeMessageHelper.setTo(tos);
            message.setSentToAddresses(StringUtils.join(tos, ",").trim());
        } else {
            StringBuilder errorMsg = new StringBuilder();

            errorMsg.append(addMessageIdToError(message) + " Message " + message.toString()
                    + " could not be sent. No valid recipient email address found: '");

            if (message.getRecipient() != null) {
                errorMsg.append(message.getRecipient().getPrimaryEmailAddress());
            } else {
                errorMsg.append(message.getRecipientEmailAddress());
            }
            LOGGER.error(errorMsg.toString());
            throw new MessagingException(errorMsg.toString());
        }

        // process BCC addresses
        try {
            InternetAddress[] bccs = getEmailAddresses(getBcc(), "bcc:", message.getId());
            if (bccs.length > 0) {
                mimeMessageHelper.setBcc(bccs);
                message.setSentBccAddresses(StringUtils.join(bccs, ",").trim());
            }
        } catch (Exception exp) {
            LOGGER.warn("Unrecoverable errors were generated adding carbon copy to message: " + message.getId()
                    + "Attempt to send message still initiated.", exp);
        }

        // process CC addresses
        try {
            InternetAddress[] carbonCopies = getEmailAddresses(message.getCarbonCopy(), "cc:", message.getId());
            if (carbonCopies.length > 0) {
                mimeMessageHelper.setCc(carbonCopies);
                message.setSentCcAddresses(StringUtils.join(carbonCopies, ",").trim());
            }
        } catch (Exception exp) {
            LOGGER.warn("Unrecoverable errors were generated adding bcc to message: " + message.getId()
                    + "Attempt to send message still initiated.", exp);
        }

        mimeMessageHelper.setSubject(message.getSubject());
        mimeMessageHelper.setText(message.getBody());
        mimeMessage.setContent(message.getBody(), "text/html");

        send(mimeMessage);

        message.setSentDate(new Date());
        messageDao.save(message);
    } catch (final MessagingException e) {
        LOGGER.error("ERROR : sendMessage() : {}", e);
        handleSendMessageError(message);
        throw new SendFailedException(addMessageIdToError(message) + "The message parameters were invalid.", e);
    }

    LOGGER.info("END : sendMessage()");
    return true;
}

From source file:org.kuali.coeus.common.impl.mail.KcEmailServiceImpl.java

public void sendEmailWithAttachments(String from, Set<String> toAddresses, String subject,
        Set<String> ccAddresses, Set<String> bccAddresses, String body, boolean htmlMessage,
        List<EmailAttachment> attachments) {

    if (mailSender != null) {
        if (CollectionUtils.isEmpty(toAddresses) && CollectionUtils.isEmpty(ccAddresses)
                && CollectionUtils.isEmpty(bccAddresses)) {
            return;
        }// ww w .ja  v  a2 s.c  o  m

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;

        try {
            helper = new MimeMessageHelper(message, true, DEFAULT_ENCODING);
            helper.setFrom(from);

            if (StringUtils.isNotBlank(subject)) {
                helper.setSubject(subject);
            } else {
                LOG.warn("Sending message with empty subject.");
            }

            if (isEmailTestEnabled()) {
                helper.setText(getTestMessageBody(body, toAddresses, ccAddresses, bccAddresses), true);
                String toAddress = getEmailNotificationTestAddress();
                if (StringUtils.isNotBlank(getEmailNotificationTestAddress())) {
                    helper.addTo(toAddress);
                }
            } else {
                helper.setText(body, htmlMessage);
                if (CollectionUtils.isNotEmpty(toAddresses)) {
                    for (String toAddress : toAddresses) {
                        try {
                            helper.addTo(toAddress);
                        } catch (Exception ex) {
                            LOG.warn("Could not set to address:", ex);
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(ccAddresses)) {
                    for (String ccAddress : ccAddresses) {
                        try {
                            helper.addCc(ccAddress);
                        } catch (Exception ex) {
                            LOG.warn("Could not set to address:", ex);
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(bccAddresses)) {
                    for (String bccAddress : bccAddresses) {
                        try {
                            helper.addBcc(bccAddress);
                        } catch (Exception ex) {
                            LOG.warn("Could not set to address:", ex);
                        }
                    }
                }
            }

            if (CollectionUtils.isNotEmpty(attachments)) {
                for (EmailAttachment attachment : attachments) {
                    try {
                        helper.addAttachment(attachment.getFileName(),
                                new ByteArrayResource(attachment.getContents()), attachment.getMimeType());
                    } catch (Exception ex) {
                        LOG.warn("Could not set to address:", ex);
                    }
                }
            }
            executorService.execute(() -> mailSender.send(message));

        } catch (MessagingException ex) {
            LOG.error("Failed to create mime message helper.", ex);
        }
    } else {
        LOG.info(
                "Failed to send email due to inability to obtain valid email mailSender, please check your configuration.");
    }
}

From source file:org.kuali.kra.service.impl.KcEmailServiceImpl.java

public void sendEmailWithAttachments(String from, Set<String> toAddresses, String subject,
        Set<String> ccAddresses, Set<String> bccAddresses, String body, boolean htmlMessage,
        List<EmailAttachment> attachments) {
    JavaMailSender sender = createSender();

    if (sender != null) {
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = null;

        try {//ww  w.j  a v  a 2 s  .  co m
            helper = new MimeMessageHelper(message, true, DEFAULT_ENCODING);
            helper.setFrom(from);

            if (CollectionUtils.isNotEmpty(toAddresses)) {
                for (String toAddress : toAddresses) {
                    helper.addTo(toAddress);
                }
            }

            if (StringUtils.isNotBlank(subject)) {
                helper.setSubject(subject);
            } else {
                LOG.warn("Sending message with empty subject.");
            }

            helper.setText(body, htmlMessage);

            if (CollectionUtils.isNotEmpty(ccAddresses)) {
                for (String ccAddress : ccAddresses) {
                    helper.addCc(ccAddress);
                }
            }

            if (CollectionUtils.isNotEmpty(bccAddresses)) {
                for (String bccAddress : bccAddresses) {
                    helper.addBcc(bccAddress);
                }
            }

            if (CollectionUtils.isNotEmpty(attachments)) {
                for (EmailAttachment attachment : attachments) {
                    helper.addAttachment(attachment.getFileName(),
                            new ByteArrayResource(attachment.getContents()), attachment.getMimeType());
                }
            }

            sender.send(message);
        } catch (MessagingException ex) {
            LOG.error("Failed to create mime message helper.", ex);
        } catch (Exception e) {
            LOG.error("Failed to send email.", e);
        }
    } else {
        LOG.info(
                "Failed to send email due to inability to obtain valid email sender, please check your configuration.");
    }
}

From source file:org.mifosplatform.infrastructure.reportmailingjob.service.ReportMailingJobEmailServiceImpl.java

@Override
public void sendEmailWithAttachment(ReportMailingJobEmailData reportMailingJobEmailData) {
    try {//from  www .j av  a2 s  .co m
        // get all ReportMailingJobConfiguration objects from the database
        this.reportMailingJobConfigurationDataCollection = this.reportMailingJobConfigurationReadPlatformService
                .retrieveAllReportMailingJobConfigurations();

        JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
        javaMailSenderImpl.setHost(this.getReportSmtpServer());
        javaMailSenderImpl.setPort(this.getRerportSmtpPort());
        javaMailSenderImpl.setUsername(this.getReportSmtpUsername());
        javaMailSenderImpl.setPassword(this.getReportSmtpPassword());
        javaMailSenderImpl.setJavaMailProperties(this.getJavaMailProperties());

        MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        mimeMessageHelper.setTo(reportMailingJobEmailData.getTo());
        mimeMessageHelper.setFrom(this.getReportSmtpFromAddress());
        mimeMessageHelper.setText(reportMailingJobEmailData.getText());
        mimeMessageHelper.setSubject(reportMailingJobEmailData.getSubject());

        if (reportMailingJobEmailData.getAttachment() != null) {
            mimeMessageHelper.addAttachment(reportMailingJobEmailData.getAttachment().getName(),
                    reportMailingJobEmailData.getAttachment());
        }

        javaMailSenderImpl.send(mimeMessage);
    }

    catch (MessagingException e) {
        // handle the exception
        e.printStackTrace();
    }
}