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

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

Introduction

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

Prototype

public MimeMessageHelper(MimeMessage mimeMessage, int multipartMode) throws MessagingException 

Source Link

Document

Create a new MimeMessageHelper for the given MimeMessage, in multipart mode (supporting alternative texts, inline elements and attachments) if requested.

Usage

From source file:cherry.foundation.mail.MailSendHandlerImpl.java

private void send(final SimpleMailMessage msg, final AttachmentPreparator preparator) {
    if (preparator == null) {
        mailSender.send(msg);//from www . jav a  2  s  .co  m
    } else {
        mailSender.send(new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
                helper.setTo(msg.getTo());
                helper.setCc(msg.getCc());
                helper.setBcc(msg.getBcc());
                helper.setFrom(msg.getFrom());
                helper.setSubject(msg.getSubject());
                helper.setText(msg.getText());
                preparator.prepare(new Attachment(helper));
            }
        });
    }
}

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 a  2  s .  c  om

    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:org.appverse.web.framework.backend.api.services.integration.impl.live.MailIntegrationServiceImpl.java

@Override
@SuppressWarnings("unchecked")
public void sendMail(String from, String[] to, String[] copyTo, String subject, String templateLocation,
        Map model) throws Exception {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);/*from www.  j a  v  a2s. c  o m*/
    helper.setTo(to);
    if (copyTo != null) {
        helper.setCc(copyTo);
    }
    helper.setSubject(subject);
    String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, ENCODING, templateLocation,
            model);
    helper.setText(text, true);
    try {
        this.mailSender.send(message);
    } catch (MailSendException sendMailException) {
        Exception[] messageExceptions = sendMailException.getMessageExceptions();
        for (Exception messageException : messageExceptions) {
            if (messageException instanceof SendFailedException) {
                SendFailedException sendFailedException = (SendFailedException) messageException;
                if (sendFailedException.getMessage().equals(INVALID_ADDRESSES)) {
                    Address[] invalidAddresses = sendFailedException.getInvalidAddresses();
                    List<String> invalidAddressList = new ArrayList<String>();
                    for (Address invalidAddress : invalidAddresses) {
                        String invalidAddressString = invalidAddress.toString();
                        invalidAddressList.add(invalidAddressString);
                    }
                    List<String> validToAdressesList = new ArrayList<String>();
                    if (to != null && to.length > 0) {
                        for (String address : to) {
                            if (!invalidAddressList.contains(address)) {
                                validToAdressesList.add(address);
                            }
                        }
                    }

                    List<String> validCopyToAdressesList = new ArrayList<String>();
                    if (copyTo != null && copyTo.length > 0) {
                        for (String address : copyTo) {
                            if (!invalidAddressList.contains(address)) {
                                validCopyToAdressesList.add(address);
                            }
                        }
                    }

                    String[] validToAdressesArray = new String[validToAdressesList.size()];
                    validToAdressesList.toArray(validToAdressesArray);
                    helper.setTo(validToAdressesList.toArray(validToAdressesArray));

                    String[] validCopyToAdressesArray = new String[validCopyToAdressesList.size()];
                    validCopyToAdressesList.toArray(validCopyToAdressesArray);
                    helper.setCc(validCopyToAdressesList.toArray(validCopyToAdressesArray));
                    for (String invalidAddress : invalidAddressList) {
                        logger.error("Mail not sended to " + invalidAddress + "due its a invalid address");
                    }
                    this.mailSender.send(message);
                }
            }
        }
    }
}

From source file:net.bafeimao.umbrella.web.test.MailTests.java

@Test
public void testSendMailWithInlineImage() throws MessagingException {
    // ?,???html//www .  j  a  v  a2 s. c o m
    MimeMessage mailMessage = senderImpl.createMimeMessage();
    // ?boolean,?MimeMessageHelpertrue?
    // multipart?
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true);

    // 
    messageHelper.setTo("29283212@qq.com");
    messageHelper.setFrom("29283212@qq.com");
    messageHelper.setSubject("!?");
    // true ?HTML?
    messageHelper.setText("<html><head></head><body><h1>hello!!spring image html mail</h1>"
            + "<img src=\"cid:aaa\"/></body></html>", true);

    FileSystemResource img = new FileSystemResource(new File(imagePath));

    messageHelper.addInline("aaa", img);

    // ??
    senderImpl.send(mailMessage);

    System.out.println("???..");
}

From source file:dk.nsi.haiba.epimibaimporter.email.EmailSender.java

private void sendText(final String subject, final String nonHtml) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        @Override//from   w  w  w.  j  a v  a 2s.  c  o  m
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setValidateAddresses(true);

            String[] split = to_commaseparated.split(",");
            for (String emailAddress : split) {
                emailAddress = emailAddress.trim();
                try {
                    log.trace("adding " + emailAddress);
                    messageHelper.addTo(emailAddress);
                    log.trace("added " + emailAddress);
                } catch (MessagingException e) {
                    log.error("unable to parse email address from " + emailAddress, e);
                }
            }
            messageHelper.setFrom(from);
            messageHelper.setSubject(subject);
            messageHelper.setText(nonHtml, false);
        }
    };
    javaMailSender.send(preparator);
}

From source file:com.realdolmen.rdfleet.scheduling.ScheduledTasks.java

/**
 * Helper method to send an email./* w  w w .java2s  .c om*/
 *
 * @param to      the receiver of the email
 * @param subject the subject of the email
 * @param body    the body of the email
 * @throws MessagingException
 */
private void sendMail(String to, String subject, String body) throws MessagingException {
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setSubject(subject);
    helper.setTo(to);
    helper.setText(body, true);
    javaMailSender.send(message);
}

From source file:org.musicrecital.service.MailEngine.java

/**
 * Convenience method for sending messages with attachments.
 * //from  ww w  .j  a  v a  2  s .co m
 * @param recipients array of e-mail addresses
 * @param sender e-mail address of sender
 * @param resource attachment from classpath
 * @param bodyText text in e-mail
 * @param subject subject of e-mail
 * @param attachmentName name for attachment
 * @throws MessagingException thrown when can't communicate with SMTP server
 */
public void sendMessage(String[] recipients, String sender, ClassPathResource resource, String bodyText,
        String subject, String attachmentName) throws MessagingException {
    MimeMessage message = ((JavaMailSenderImpl) mailSender).createMimeMessage();

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

    helper.setTo(recipients);

    // use the default sending if no sender specified
    if (sender == null) {
        helper.setFrom(defaultFrom);
    } else {
        helper.setFrom(sender);
    }

    helper.setText(bodyText);
    helper.setSubject(subject);

    helper.addAttachment(attachmentName, resource);

    ((JavaMailSenderImpl) mailSender).send(message);
}

From source file:de.whs.poodle.services.EmailService.java

public void sendMail(Instructor from, String toUsername, List<String> bccUsernames, boolean senderBcc,
        String subject, String text, boolean setNoReply) throws MessagingException {
    if (bccUsernames == null)
        bccUsernames = new ArrayList<>();

    if (toUsername == null && bccUsernames.isEmpty()) {
        log.info("sendMail(): no recipients, aborting.");
        return;/*from w ww.j a v a  2  s. c o m*/
    }

    // may be empty if bccUsernames was not specified
    List<String> bccEmails = getEmailsForUsernames(bccUsernames);

    String fromEmail = getEmailForUsername(from.getUsername());

    // create "from" as "FirstName LastName <email@w-hs.de>"
    String fromStr = String.format("%s %s <%s>", from.getFirstName(), from.getLastName(), fromEmail);

    if (senderBcc)
        bccEmails.add(fromEmail);

    // create MimeMessage
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8");

    helper.setSubject("[Poodle] " + subject);
    helper.setFrom(fromStr);

    if (toUsername != null) {
        String toEmail = getEmailForUsername(toUsername);
        helper.setTo(toEmail);
    }

    if (!bccEmails.isEmpty())
        helper.setBcc(bccEmails.toArray(new String[0]));

    if (setNoReply)
        helper.setReplyTo(poodle.getEmailNoReplyAddress());

    helper.setText(text);

    mailSender.send(mimeMessage);
}

From source file:com.autentia.wuija.mail.MailService.java

/**
 * send an e-mail/*from  w  w  w  .  java  2 s .c o m*/
 * 
 * @param to recipient e-mail
 * @param subject the subject of the e-mail
 * @param text the body of the e-mail
 * @param attachments an array of it
 * @throws EmailException if the e-mail cannot be prepare or send.
 */
public void send(String to, String subject, String text, File... attachments) {
    Assert.hasLength(to, "email 'to' needed");
    Assert.hasLength(subject, "email 'subject' needed");
    Assert.hasLength(text, "email 'text' needed");

    if (log.isDebugEnabled()) {
        final boolean usingPassword = StringUtils.isNotBlank(mailSender.getPassword());
        log.debug("Sending email to: '" + to + "' [through host: '" + mailSender.getHost() + ":"
                + mailSender.getPort() + "', username: '" + mailSender.getUsername() + "' usingPassword:"
                + usingPassword + "].");
        log.debug("isActive: " + active);
    }
    if (!active) {
        return;
    }

    final MimeMessage message = mailSender.createMimeMessage();

    try {
        // use the true flag to indicate you need a multipart message
        final MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setFrom(getFrom());
        helper.setText(text);

        if (attachments != null) {
            for (int i = 0; i < attachments.length; i++) {
                // let's attach each file
                final FileSystemResource file = new FileSystemResource(attachments[i]);
                helper.addAttachment(attachments[i].getName(), file);
                if (log.isDebugEnabled()) {
                    log.debug("File '" + file + "' attached.");
                }
            }
        }

    } catch (MessagingException e) {
        final String msg = "Cannot prepare email message : " + subject + ", to: " + to;
        log.error(msg, e);
        throw new MailPreparationException(msg, e);
    }
    this.mailSender.send(message);
}

From source file:com.cfitzarl.cfjwed.service.impl.EmailDispatchingServiceImpl.java

/** {@inheritDoc} **/
@Override//from   w  w  w .  ja  v  a2s.c  o m
public void send(String to, String subject, String template, Map<String, Object> attrs) {
    // Add message source decorator to attributes list for localization
    attrs.put("localeSource", localizationService);

    String htmlFilename = String.format("/email-templates/%s-html.vm", template);
    String textFilename = String.format("/email-templates/%s-text.vm", template);

    String htmlContent = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, htmlFilename, "UTF-8",
            attrs);
    String textContent = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, textFilename, "UTF-8",
            attrs);

    try {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        String fromEmail = configDao.findByKey(ConfigKey.EMAIL).getValue();
        String fromTitle = configDao.findByKey(ConfigKey.TITLE).getValue();

        String from = String.format("%s <%s>", fromTitle, fromEmail);

        helper.setTo(to);
        helper.setSubject(subject);
        helper.setFrom(from);
        helper.setReplyTo(from);
        helper.setText(textContent, htmlContent);

        taskExecutor.submit(new MailRunner(message, javaMailSender));
    } catch (MessagingException e) {
        LOGGER.error("Error generating mail message", e);
    }
}