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

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

Introduction

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

Prototype

MimeMessagePreparator

Source Link

Usage

From source file:com.mobileman.projecth.business.impl.MailManagerImpl.java

/** 
 * {@inheritDoc}//  w w w . j a va  2s  .c o  m
 * @see com.mobileman.projecth.business.MailManager#sendTellAFriendMessage(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void sendTellAFriendMessage(final String senderName, final String senderEmail,
        final String receiverEmails, final String body) {
    if (log.isDebugEnabled()) {
        log.debug("sendMessage(" + senderName + ", " + senderEmail + ", " + receiverEmails + ", " + body
                + ") - start");
    }

    if (senderEmail == null || senderEmail.trim().length() == 0) {
        throw new MailException(MailException.Reason.SENDER_EMAIL_MISSING);
    }

    if (receiverEmails == null || receiverEmails.trim().length() == 0) {
        throw new MailException(MailException.Reason.SENDER_EMAIL_MISSING);
    }

    final String[] senderData = { "", "", "" };

    final String[] receivers = receiverEmails.split("[,]");
    for (int i = 0; i < receivers.length; i++) {
        final int idx = i;
        MimeMessagePreparator preparator = new MimeMessagePreparator() {

            /**
             * {@inheritDoc}
             * @see org.springframework.mail.javamail.MimeMessagePreparator#prepare(javax.mail.internet.MimeMessage)
             */
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                if (log.isDebugEnabled()) {
                    log.debug("$MimeMessagePreparator.prepare(MimeMessage) - start"); //$NON-NLS-1$
                }

                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING);
                messageHelper.setSentDate(new Date());

                Map<String, Object> model = new HashMap<String, Object>();
                model.put("body-text", body);
                String htmlMessage = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                        "tell-a-friend-email-body.vm", model);
                String textMessage = HTMLTextParser.htmlToText(htmlMessage);
                messageHelper.setText(textMessage, htmlMessage);
                senderData[0] = htmlMessage;
                senderData[1] = textMessage;
                senderData[2] = "Mitteilung von projecth";

                messageHelper.setSubject(senderData[2]);
                messageHelper.setTo(receivers[idx]);
                messageHelper.setFrom(getSystemAdminEmail());

                if (log.isDebugEnabled()) {
                    log.debug("$MimeMessagePreparator.prepare(MimeMessage) - returns"); //$NON-NLS-1$
                }
            }
        };

        this.mailSender.send(preparator);
    }

    this.mailSender.send(new MimeMessagePreparator() {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING);
            messageHelper.setSentDate(new Date());
            messageHelper.setText(senderData[1], senderData[0]);
            messageHelper.setSubject(senderData[2]);
            messageHelper.setTo(senderEmail);
            messageHelper.setFrom(getSystemAdminEmail());
        }
    });

    if (log.isDebugEnabled()) {
        log.debug("sendMessage(...) - end");
    }
}

From source file:com.mobileman.projecth.business.impl.MailManagerImpl.java

/** 
 * {@inheritDoc}//from   w  ww  .j a va2  s  .com
 * @see com.mobileman.projecth.business.MailManager#sendResetCredientialsEmail(User, String)
 */
@Override
public void sendNewDiseaseGroupRequestEmail(final String diseaseName, final String emailAddress,
        final UserType userType) {
    if (log.isDebugEnabled()) {
        log.debug("sendNewDiseaseGroupRequestEmail(" + diseaseName + ", " + emailAddress + ", " + userType
                + ") - start");
    }

    final Map<String, Object> model = new HashMap<String, Object>();
    model.put("disease_name", diseaseName);
    model.put("sender_email", emailAddress);
    model.put("sender_user_type", (UserType.P.equals(userType) ? "Patient" : "Arzt"));

    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            if (log.isDebugEnabled()) {
                log.debug("$MimeMessagePreparator.prepare(MimeMessage) - start"); //$NON-NLS-1$
            }

            String subject = MessageFormat.format("Neue Gesundheitsgruppe anmelden: {0}", diseaseName);

            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING);
            messageHelper.setSentDate(new Date());
            messageHelper.setTo("mitglied@projecth.com");
            messageHelper.setFrom(emailAddress);
            messageHelper.setSubject(subject);

            String htmlMessage = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "request-new-disease-group-system-email-body.vm", model);
            String textMessage = HTMLTextParser.htmlToText(htmlMessage);
            messageHelper.setText(textMessage, htmlMessage);

            if (log.isDebugEnabled()) {
                log.debug("$MimeMessagePreparator.prepare(MimeMessage) - returns"); //$NON-NLS-1$
            }
        }
    };

    this.mailSender.send(preparator);

    preparator = new MimeMessagePreparator() {

        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            if (log.isDebugEnabled()) {
                log.debug("$MimeMessagePreparator.prepare(MimeMessage) - start"); //$NON-NLS-1$
            }

            String subject = MessageFormat.format("Anfrage zur Erweiterung von projecth mit {0}", diseaseName);

            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING);
            messageHelper.setSentDate(new Date());
            messageHelper.setTo(emailAddress);
            messageHelper.setFrom("gesundheitsgruppen@projecth.com");
            messageHelper.setSubject(subject);

            String htmlMessage = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "request-new-disease-group-sender-email-body.vm", model);
            String textMessage = HTMLTextParser.htmlToText(htmlMessage);
            messageHelper.setText(textMessage, htmlMessage);

            if (log.isDebugEnabled()) {
                log.debug("$MimeMessagePreparator.prepare(MimeMessage) - returns"); //$NON-NLS-1$
            }
        }
    };

    this.mailSender.send(preparator);

    if (log.isDebugEnabled()) {
        log.debug("sendNewDiseaseGroupRequestEmail(...) - end");
    }
}

From source file:nl.surfnet.coin.teams.control.AddMemberController.java

/**
 * Sends an email based on the {@link Invitation}
 *
 * @param invitation {@link Invitation} that contains the necessary data
 * @param subject    of the email//from w  w w . j ava2s. c  om
 * @param inviter    {@link Person} who sends the invitation
 * @param locale     {@link Locale} for the mail
 */
protected void sendInvitationByMail(final Invitation invitation, final String subject, final Person inviter,
        final Locale locale) {

    final String html = composeInvitationMailMessage(invitation, inviter, locale, "html");
    final String plainText = composeInvitationMailMessage(invitation, inviter, locale, "plaintext");

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.addHeader("Precedence", "bulk");
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(invitation.getEmail()));
            mimeMessage.setFrom(new InternetAddress(environment.getSystemEmail()));
            mimeMessage.setSubject(subject);

            MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html);
            mimeMessage.setContent(rootMixedMultipart);
        }
    };

    mailService.sendAsync(preparator);
}

From source file:it.jugpadova.blo.JuggerBo.java

/**
 * General jugger mail sender/*  w w w .  j av a2 s .c  o m*/
 *
 * @param jugger
 * @param baseUrl
 * @param subject
 * @param oneWayCode
 * @param template
 */
private void sendEmail(final Jugger jugger, final String baseUrl, final String subject, final String oneWayCode,
        final String template) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @SuppressWarnings(value = "unchecked")
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(jugger.getEmail());
            message.setFrom(conf.getConfirmationSenderEmailAddress());
            message.setSubject(subject);
            Map model = new HashMap();
            model.put("jugger", jugger);
            model.put("baseUrl", baseUrl);
            model.put("oneWayCode", URLEncoder.encode(oneWayCode, "UTF-8"));
            model.put("username", URLEncoder.encode(jugger.getUser().getUsername(), "UTF-8"));
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model);
            message.setText(text, true);
        }
    };
    this.mailSender.send(preparator);
}

From source file:net.malariagen.alfresco.action.CustomMailAction.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());
            }// w w  w  . ja v  a  2 s  . c  o 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);
            }

            String listHeaders = (String) ruleAction.getParameterValue(PARAM_LIST_ID);
            if (listHeaders != null) {
                mimeMessage.setHeader("List-Id",
                        "<" + listHeaders + "." + sysAdminParams.getAlfrescoHost() + ">");
                mimeMessage.setHeader("X-Auto-Response-Suppress", "All");
                mimeMessage.setHeader("Precedence", "list");
                mimeMessage.setHeader("auto-submitted", "auto-generated");
            }

            // set recipient
            // I don't think this is used - see getRecipients in parent
            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) {
                                    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);
                    }
                    setReplyTo(ruleAction, messageRef, 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);
                        setReplyTo(ruleAction, messageRef, fromDefaultAddress);
                    } else {
                        // from system or user does not have email address
                        messageRef[0].setFrom(fromDefaultAddress);
                        setReplyTo(ruleAction, messageRef, fromDefaultAddress);
                    }
                }

            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("from not enabled - sending from default address:" + fromDefaultAddress);
                }
                // from is not enabled.
                messageRef[0].setFrom(fromDefaultAddress);
                setReplyTo(ruleAction, messageRef, 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);
            }

        }

        private void setReplyTo(final Action ruleAction, final MimeMessageHelper[] messageRef, String from)
                throws MessagingException {
            // ResponseNode can be a Long as well as Text
            Object responseNode = ruleAction.getParameterValue(PARAM_RESPONSE_NODE);

            if (responseNode != null) {
                // Assuming address is valid...
                String[] parts = from.split("@");
                messageRef[0].setReplyTo(parts[0] + "+" + responseNode + "@" + parts[1]);
            }
        }
    };
    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:nl.surfnet.coin.teams.control.DetailTeamController.java

/**
 * Notifies the user that requested to join a team that his request has been
 * declined/*from  w ww  .ja  v a 2  s  .  c  o  m*/
 *
 * @param memberToAdd {@link Person} that wanted to join the team
 * @param team        {@link Team} he wanted to join
 * @param locale      {@link Locale}
 */
private void sendDeclineMail(final Person memberToAdd, final Team team, final Locale locale) {
    final String subject = messageSource.getMessage("request.mail.declined.subject", null, locale);
    final String html = composeDeclineMailMessage(team, locale, "html");
    final String plainText = composeDeclineMailMessage(team, locale, "plaintext");

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.addHeader("Precedence", "bulk");

            mimeMessage.setFrom(new InternetAddress(teamEnvironment.getSystemEmail()));
            mimeMessage.setRecipients(Message.RecipientType.TO, convertEmailAdresses(memberToAdd.getEmails()));
            mimeMessage.setSubject(subject);

            MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html);
            mimeMessage.setContent(rootMixedMultipart);
        }
    };

    mailService.sendAsync(preparator);
}

From source file:nl.surfnet.coin.teams.control.DetailTeamController.java

/**
 * Notifies the user that requested to join a team that his request has been
 * declined//  w w w .j ava2 s  .co  m
 *
 * @param memberToAdd {@link Person} that wanted to join the team
 * @param team        {@link Team} he wanted to join
 * @param locale      {@link Locale}
 */
private void sendAcceptMail(final Person memberToAdd, final Team team, final Locale locale) {
    final String subject = messageSource.getMessage("request.mail.accepted.subject", null, locale);
    final String html = composeAcceptMailMessage(team, locale, "html");
    final String plainText = composeAcceptMailMessage(team, locale, "plaintext");

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.addHeader("Precedence", "bulk");

            mimeMessage.setFrom(new InternetAddress(teamEnvironment.getSystemEmail()));
            mimeMessage.setRecipients(Message.RecipientType.TO, convertEmailAdresses(memberToAdd.getEmails()));
            mimeMessage.setSubject(subject);

            MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html);
            mimeMessage.setContent(rootMixedMultipart);
        }
    };

    mailService.sendAsync(preparator);
}

From source file:it.jugpadova.blo.EventBo.java

private void sendConfirmationEmail(final Event event, final Participant participant, final String baseUrl) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @SuppressWarnings(value = "unchecked")
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(participant.getEmail());
            message.setFrom(conf.getConfirmationSenderEmailAddress());
            message.setSubject("Please confirm event registration");
            Map model = new HashMap();
            model.put("participant", participant);
            model.put("event", event);
            model.put("baseUrl", baseUrl);
            model.put("confirmationCode", URLEncoder.encode(participant.getConfirmationCode(), "UTF-8"));
            model.put("email", URLEncoder.encode(participant.getEmail(), "UTF-8"));
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "it/jugpadova/registration-confirmation.vm", model);
            message.setText(text, true);
        }//w ww  .  ja v  a 2  s.co m
    };
    this.mailSender.send(preparator);
}

From source file:au.org.theark.core.service.ArkCommonServiceImpl.java

public void sendEmail(final SimpleMailMessage simpleMailMessage) throws MailSendException, VelocityException {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(simpleMailMessage.getTo());

            // The "from" field is required
            if (simpleMailMessage.getFrom() == null) {
                simpleMailMessage.setFrom(Constants.ARK_ADMIN_EMAIL);
            }/*w  w w .ja  va 2s. c  om*/

            message.setFrom(simpleMailMessage.getFrom());
            message.setSubject(simpleMailMessage.getSubject());

            // Map all the fields for the email template
            Map<String, Object> model = new HashMap<String, Object>();

            // Add the host name into the footer of the email
            String host = InetAddress.getLocalHost().getHostName();

            // Message title
            model.put("title", "Message from The ARK");
            // Message header
            model.put("header", "Message from The ARK");
            // Message subject
            model.put("subject", simpleMailMessage.getSubject());
            // Message text
            model.put("text", simpleMailMessage.getText());
            // Hostname in message footer
            model.put("host", host);

            // TODO: Add inline image(s)??
            // Add inline image header
            // FileSystemResource res = new FileSystemResource(new
            // File("c:/Sample.jpg"));
            // message.addInline("bgHeaderImg", res);

            // Set up the email text
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "au/org/theark/core/velocity/resetPasswordEmail.vm", model);
            message.setText(text, true);
        }
    };

    // send out the email
    javaMailSender.send(preparator);
}

From source file:ome.services.mail.MailUtil.java

/**
 * Main method which takes typical email fields as arguments, to prepare and
 * populate the given new MimeMessage instance and send.
 *
 * @param from/*from  w  ww  .j a  v  a2  s.  c  o  m*/
 *            email address message is sent from
 * @param to
 *            email address message is sent to
 * @param topic
 *            topic of the message
 * @param body
 *            body of the message
 * @param html
 *            flag determines the content type to apply.
 * @param ccrecipients
 *            list of email addresses message is sent as copy to
 * @param bccrecipients
 *            list of email addresses message is sent as blind copy to
 */
public void sendEmail(final String from, final String to, final String topic, final String body,
        final boolean html, final List<String> ccrecipients, final List<String> bccrecipients) {

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {

            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setText(body, html);
            message.setFrom(from);
            message.setSubject(topic);
            message.setTo(to);
            if (ccrecipients != null && !ccrecipients.isEmpty()) {
                message.setCc(ccrecipients.toArray(new String[ccrecipients.size()]));
            }

            if (bccrecipients != null && !bccrecipients.isEmpty()) {
                message.setCc(bccrecipients.toArray(new String[bccrecipients.size()]));
            }
        }

    };

    this.mailSender.send(preparator);
}