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

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

Introduction

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

Prototype

public final MimeMessage getMimeMessage() 

Source Link

Document

Return the underlying MimeMessage object.

Usage

From source file:business.services.MailService.java

public void sendPasswordRecoveryToken(NewPasswordRequest npr) {
    try {//from  www.  j av a2  s. com
        MimeMessageHelper message = new MimeMessageHelper(mailSender.createMimeMessage());
        String recipient = npr.getUser().getContactData().getEmail();
        message.setTo(recipient);
        message.setFrom(getFrom(), fromName);
        message.setReplyTo(replyAddress, replyName);
        message.setSubject(passwordRecoverySubject);
        String passwordRecoveryLink = getLink("/#/login/reset-password/" + npr.getToken());
        message.setText(String.format(passwordRecoveryTemplate, passwordRecoveryLink));
        log.info("Sending password recovery token to " + recipient + ".");
        mailSender.send(message.getMimeMessage());
    } catch (MessagingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    }
}

From source file:business.services.MailService.java

@Transactional
public void notifyScientificCouncil(@NotNull RequestRepresentation request) {
    log.info("Notify scientic council for request " + request.getProcessInstanceId() + ".");

    List<User> members = userService.findScientificCouncilMembers();
    for (User member : members) {
        log.info("Sending notification to user " + member.getUsername());
        try {//from   w  w  w.  j a va  2s. c o  m
            MimeMessageHelper message = new MimeMessageHelper(mailSender.createMimeMessage());
            message.setTo(member.getContactData().getEmail());
            message.setFrom(getFrom(), fromName);
            message.setReplyTo(replyAddress, replyName);
            message.setSubject(String.format("Nieuwe PALGA-aanvraag aan u voorgelegd, aanvraagnummer: %s",
                    request.getRequestNumber()));
            String requestLink = getLink("/#/request/view/" + request.getProcessInstanceId());
            message.setText(String.format(scientificCouncilNotificationTemplate, requestLink));
            mailSender.send(message.getMimeMessage());
        } catch (MessagingException e) {
            log.error(e.getMessage());
            throw new EmailError("Email error: " + e.getMessage());
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
            throw new EmailError("Email error: " + e.getMessage());
        }
    }
}

From source file:hornet.framework.mail.MailServiceImpl.java

/**
 * Adds the extra smtp field.//from   w w w .  j a va  2s  .co m
 *
 * @param paramMap
 *            the param map
 * @param helper
 *            the helper
 * @throws MessagingException
 *             the messaging exception
 */
protected void addExtraSmtpField(final Map<String, Object> paramMap, final MimeMessageHelper helper)
        throws MessagingException {

    if (paramMap != null) {
        if (paramMap.containsKey(SMTP_HEADER_REPLYTO)) {
            helper.setReplyTo((String) paramMap.get(SMTP_HEADER_REPLYTO));
        }
        if (paramMap.containsKey(SMTP_HEADER_BCC)) {
            helper.setBcc((String) paramMap.get(SMTP_HEADER_BCC));
        }
        if (paramMap.containsKey(SMTP_HEADER_CC)) {
            helper.setCc((String) paramMap.get(SMTP_HEADER_CC));
        }
        if (paramMap.containsKey(SMTP_HEADER_PRIORITY)) {
            helper.setPriority((Integer) paramMap.get(SMTP_HEADER_PRIORITY));
        }
        if (paramMap.containsKey(SMTP_HEADER_RETURNPATH)) {
            ((SMTPMessage) helper.getMimeMessage())
                    .setEnvelopeFrom((String) paramMap.get(SMTP_HEADER_RETURNPATH));
        }
        if (paramMap.containsKey(SMTP_ATTACHMENT_CONTENU)) {
            helper.addAttachment((String) paramMap.get(SMTP_ATTACHMENT_NOM),
                    (InputStreamSource) paramMap.get(SMTP_ATTACHMENT_CONTENU));
        }
    }
}

From source file:be.roots.taconic.pricingguide.service.MailServiceImpl.java

@Override
public void sendReport(DateTime lastMonth, String filename, byte[] report) throws MessagingException {

    final MimeMessageHelper helper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);

    helper.setFrom(fromEmail);/*from w w w  .j  av  a2 s  .c o  m*/

    if (StringUtils.isEmpty(testEmail)) {
        helper.setTo(reportRecipientEmail.split(","));
    } else {
        helper.setTo(testEmail.split(","));
    }

    if (!StringUtils.isEmpty(bccEmail)) {
        helper.setBcc(bccEmail.split(","));
    }

    helper.setSubject(documentTitle + " requests for " + lastMonth.toString(DefaultUtil.FORMAT_MONTH));

    final String body = "Dear<br>" + "<br>" + "Attached you find the overview of " + documentTitle
            + " requests for " + lastMonth.toString(DefaultUtil.FORMAT_MONTH) + ".<br>" + "<br>"
            + "Taconic Biosciences, Inc.<br>" + "One Hudson City Centre<br>" + "Hudson, New York 12534<br>"
            + "North America +1 888 822-6642<br>" + "Europe +45 70 23 04 05<br>" + "info@taconic.com<br>"
            + "www.taconic.com";

    helper.setText(body, true);

    helper.addAttachment(filename, new ByteArrayResource(report));

    javaMailSender.send(helper.getMimeMessage());

}

From source file:be.roots.taconic.pricingguide.service.MailServiceImpl.java

@Override
public void sendMail(Contact contact, byte[] pricingGuide) throws MessagingException {

    final MimeMessageHelper helper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);

    helper.setFrom(fromEmail);//from  w w  w .j  a va  2s . c o  m

    if (StringUtils.isEmpty(testEmail)) {
        helper.setTo(contact.getEmail());
    } else {
        helper.setTo(testEmail.split(","));
    }

    if (!StringUtils.isEmpty(bccEmail)) {
        helper.setBcc(bccEmail.split(","));
    }

    helper.setSubject("Your " + documentTitle);

    final String body = "Dear " + contact.getFullName() + ",<br>" + "<br>" + "Your " + documentTitle
            + " is attached.<br>" + "<br>"
            + "Please <a href=\"http:www.taconic.com/customer-service/contact-us\">contact us</a> for any additional information.<br>"
            + "<br>" + "Taconic Biosciences, Inc.<br>" + "One Hudson City Centre<br>"
            + "Hudson, New York 12534<br>" + "North America +1 888 822-6642<br>" + "Europe +45 70 23 04 05<br>"
            + "info@taconic.com<br>" + "www.taconic.com";

    helper.setText(body, true);

    helper.addAttachment(documentFileName, new ByteArrayResource(pricingGuide));

    javaMailSender.send(helper.getMimeMessage());

}

From source file:business.services.MailService.java

public void notifyLab(@NotNull LabRequestRepresentation labRequest) {
    log.info("Notify lab for lab request " + labRequest.getId() + ".");

    Lab lab = labRequest.getLab();//from  w  w w.j  a v a 2 s  . co m
    if (lab.getEmailAddresses() == null || lab.getEmailAddresses().isEmpty()) {
        log.warn("No email address set for lab " + lab.getNumber());
        return;
    }
    String recipients = String.join(", ", lab.getEmailAddresses());
    log.info("Sending notification to " + recipients);
    try {
        MimeMessageHelper message = new MimeMessageHelper(mailSender.createMimeMessage());
        for (String email : lab.getEmailAddresses()) {
            message.addTo(email);
        }
        message.setFrom(getFrom(), fromName);
        message.setReplyTo(replyAddress, replyName);
        message.setSubject(String.format("PALGA-verzoek aan laboratorium, aanvraagnummer: %s",
                labRequest.getLabRequestCode()));
        String labRequestLink = getLink("/#/lab-request/view/" + labRequest.getId());
        String body = String.format(labNotificationTemplate, labRequestLink, // %1
                labRequest.getLabRequestCode(), // %2
                labRequest.getRequest().getTitle(), // %3
                labRequest.getRequesterName(), // %4
                labRequest.getRequest().getPathologistName() == null ? ""
                        : labRequest.getRequest().getPathologistName(), // %5
                labRequest.getRequesterLab().getName() // %6
        );
        message.setText(body);
        mailSender.send(message.getMimeMessage());
    } catch (MessagingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    }
}

From source file:alfio.manager.system.SmtpMailer.java

@Override
public void send(Event event, String to, List<String> cc, String subject, String text, Optional<String> html,
        Attachment... attachments) {//  ww  w  . j  a  va 2s  . c  o  m
    MimeMessagePreparator preparator = (mimeMessage) -> {
        MimeMessageHelper message = html.isPresent() || !ArrayUtils.isEmpty(attachments)
                ? new MimeMessageHelper(mimeMessage, true, "UTF-8")
                : new MimeMessageHelper(mimeMessage, "UTF-8");
        message.setSubject(subject);
        message.setFrom(
                configurationManager.getRequiredValue(
                        Configuration.from(event.getOrganizationId(), event.getId(), SMTP_FROM_EMAIL)),
                event.getDisplayName());
        String replyTo = configurationManager.getStringConfigValue(
                Configuration.from(event.getOrganizationId(), event.getId(), MAIL_REPLY_TO), "");
        if (StringUtils.isNotBlank(replyTo)) {
            message.setReplyTo(replyTo);
        }
        message.setTo(to);
        if (cc != null && !cc.isEmpty()) {
            message.setCc(cc.toArray(new String[cc.size()]));
        }
        if (html.isPresent()) {
            message.setText(text, html.get());
        } else {
            message.setText(text, false);
        }

        if (attachments != null) {
            for (Attachment a : attachments) {
                message.addAttachment(a.getFilename(), new ByteArrayResource(a.getSource()),
                        a.getContentType());
            }
        }

        message.getMimeMessage().saveChanges();
        message.getMimeMessage().removeHeader("Message-ID");
    };
    toMailSender(event).send(preparator);
}

From source file:net.malariagen.alfresco.action.CustomMailAction.java

private void sendEmail(final Action ruleAction, MimeMessageHelper preparedMessage) {

    try {/*ww w  .  j  av  a2 s . c o  m*/
        // Send the message unless we are in "testMode"
        if (!testMode) {
            mailService.send(preparedMessage.getMimeMessage());
            onSend();
        } else {
            lastTestMessage = preparedMessage.getMimeMessage();
            testSentCount++;
        }
    } catch (MailException e) {
        onFail();
        String to = (String) ruleAction.getParameterValue(PARAM_TO);
        if (to == null) {
            Object obj = ruleAction.getParameterValue(PARAM_TO_MANY);
            if (obj != null) {
                to = obj.toString();
            }
        }

        // always log the failure
        logger.error("Failed to send email to " + to + " : " + e);

        // optionally ignore the throwing of the exception
        Boolean ignoreError = (Boolean) ruleAction.getParameterValue(PARAM_IGNORE_SEND_FAILURE);
        if (ignoreError == null || ignoreError.booleanValue() == false) {
            throw new AlfrescoRuntimeException("Failed to send email to:" + to);
        }
    }
}

From source file:net.malariagen.alfresco.action.CustomMailAction.java

/**
 * Send a test message/*from w ww  .  j a v a2s  .  c  om*/
 * 
 * @return true, message sent
 * @throws AlfrescoRuntimeException
 */
public boolean sendTestMessage() {
    if (testMessageTo == null || testMessageTo.length() == 0) {
        throw new AlfrescoRuntimeException("email.outbound.err.test.no.to");
    }
    if (testMessageSubject == null || testMessageSubject.length() == 0) {
        throw new AlfrescoRuntimeException("email.outbound.err.test.no.subject");
    }
    if (testMessageText == null || testMessageText.length() == 0) {
        throw new AlfrescoRuntimeException("email.outbound.err.test.no.text");
    }
    Map<String, Serializable> params = new HashMap<String, Serializable>();
    params.put(PARAM_TO, testMessageTo);
    params.put(PARAM_SUBJECT, testMessageSubject);
    params.put(PARAM_TEXT, testMessageText);

    Action ruleAction = serviceRegistry.getActionService().createAction(NAME, params);

    MimeMessageHelper message = prepareEmail(ruleAction, null,
            new Pair<String, Locale>(testMessageTo, getLocaleForUser(testMessageTo)), getFrom(ruleAction));
    try {
        mailService.send(message.getMimeMessage());
        onSend();
    } catch (MailException me) {
        onFail();
        StringBuffer txt = new StringBuffer();

        txt.append(me.getClass().getName() + ", " + me.getMessage());

        Throwable cause = me.getCause();
        while (cause != null) {
            txt.append(", ");
            txt.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        Object[] args = { testMessageTo, txt.toString() };
        throw new AlfrescoRuntimeException("email.outbound.err.send.failed", args, me);
    }

    return true;
}