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

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

Introduction

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

Prototype

public void setFrom(String from) throws MessagingException 

Source Link

Usage

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

/**
 * Send Email Invitation./*from  w ww  . jav a  2s  . c  o  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 va 2s.c om
 * @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.//from  w  ww  .j  a v  a2s  .c o  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.//from  w  ww. ja  v 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}//from  ww  w  . j  a v a  2 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/*  w  w  w. j ava 2s  .  co 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);
}

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

/**
 * Send Mime Email.//from   w ww.j ava2s. c  om
 * @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./* w  ww  .ja v a  2  s . 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.ssp.service.impl.MessageServiceImpl.java

@Override
@Transactional(readOnly = false)//w ww  .  ja  v a  2  s. co  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;
        }//from   www.  j  a  va 2 s . com

        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.");
    }
}