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:uk.org.funcube.fcdw.server.email.VelocityTemplateEmailSender.java

@Override
public void sendEmailUsingTemplate(final String fromAddress, final String toAddress,
        final String[] bccAddresses, final String subject, final String templateLocation,
        final Map<String, Object> model) {

    final Map<String, Object> augmentedModel = new HashMap<String, Object>(model);
    augmentedModel.put("dateTool", new DateTool());
    augmentedModel.put("numberTool", new NumberTool());
    augmentedModel.put("mathTool", new MathTool());

    final Writer writer = new StringWriter();
    VelocityEngineUtils.mergeTemplate(velocityEngine, templateLocation, augmentedModel, writer);
    final String emailBody = writer.toString();

    final MimeMessagePreparator prep = new MimeMessagePreparator() {
        @Override/*from ww w. j  av  a2s  .com*/
        public void prepare(final MimeMessage mimeMessage) throws Exception {
            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, EMAIL_CONTENT_ENCODING);
            message.setTo(toAddress);
            message.setFrom(fromAddress);
            message.setSubject(subject);
            message.setText(emailBody);

            if (!ArrayUtils.isEmpty(bccAddresses)) {
                message.setBcc(bccAddresses);
            }
        }
    };

    try {
        mailSender.send(prep);
        LOGGER.debug(String.format("Sent %3$s email To: %1$s, Bcc: %2$s", toAddress,
                ArrayUtils.toString(bccAddresses, "None"), templateLocation));
    } catch (final MailException e) {
        LOGGER.error("Could not send email " + subject, e);
        throw e;
    }
}

From source file:org.brushingbits.jnap.email.Email.java

public void prepare(MimeMessage mimeMessage) throws Exception {
    final EmailAccountInfo acc = getAccountInfo();
    boolean multipart = StringUtils.isNotBlank(getHtmlText())
            || (getInlineResources() != null && getInlineResources().size() > 0)
            || (getAttachments() != null && getAttachments().size() > 0);
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipart);
    helper.setTo(getTo());/*  w  w w  .j  a  v  a 2  s  .c o m*/
    if (getCc() != null) {
        helper.setCc(getCc());
    }
    if (getBcc() != null) {
        helper.setBcc(getBcc());
    }
    helper.setSentDate(new Date());
    helper.setSubject(i18nTextProvider.getText(getSubject()));

    // sender info
    //      if (acc != null && StringUtils.isNotBlank(acc.getFromName())) {
    //         helper.setFrom(getFrom(), i18nTextProvider.getText(acc.getFromName()));
    //      } else {
    //         helper.setFrom(getFrom());
    //      }
    if (acc != null && StringUtils.isNotBlank(acc.getReplyToEmailAddress())) {
        if (StringUtils.isNotBlank(acc.getReplyToName())) {
            helper.setReplyTo(acc.getReplyToEmailAddress(), acc.getReplyToName());
        } else {
            helper.setReplyTo(acc.getReplyToEmailAddress());
        }
    }

    final boolean hasHtmlText = StringUtils.isNotBlank(getHtmlText());
    final boolean hasText = StringUtils.isNotBlank(getText());
    if (hasHtmlText && hasText) {
        helper.setText(getText(), getHtmlText());
    } else if (hasHtmlText || hasText) {
        helper.setText(hasHtmlText ? getHtmlText() : getText());
    }

    // add inline resources
    final Map<String, Resource> inlineRes = this.getInlineResources();
    if (inlineRes != null) {
        for (String cid : inlineRes.keySet()) {
            helper.addInline(cid, inlineRes.get(cid));
        }
    }
    // add attachments
    final Map<String, Resource> attachments = this.getAttachments();
    if (attachments != null) {
        for (String attachmentName : attachments.keySet()) {
            helper.addAttachment(attachmentName, attachments.get(attachmentName));
        }
    }
}

From source file:gov.nih.nci.cabig.caaers.web.admin.DiagnosticsController.java

private boolean testSmtp(DiagnosticsCommand diagnosticsCommand) {
    boolean testResult = false;
    try {// ww w  . j  av  a 2 s .c o  m
        MimeMessage message = caaersJavaMailSender.createMimeMessage();
        message.setSubject("Test mail from caAERS Diagnostics");
        message.setFrom(new InternetAddress("caaers.app@gmail.com"));

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        String fromEmail = configuration.get(Configuration.SYSTEM_FROM_EMAIL);
        if (fromEmail == null)
            fromEmail = "admin@semanticbits.com";
        helper.setTo(fromEmail);
        caaersJavaMailSender.send(message);
        testResult = true;
    } catch (Exception e) {
        //log.error(" Error in sending email , please check the confiuration " + e);
        diagnosticsCommand.setSmtpException(e);
        testResult = false;
    }
    return testResult;
}

From source file:io.lavagna.model.MailConfig.java

public void send(final String to, final String subject, final String text, final String html) {

    toMailSender().send(new MimeMessagePreparator() {
        @Override//from w  w w  .j  a v a 2 s  .  co m
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = html == null ? new MimeMessageHelper(mimeMessage, "UTF-8")
                    : new MimeMessageHelper(mimeMessage, true, "UTF-8");
            message.setSubject(subject);
            message.setFrom(getFrom());
            message.setTo(to);
            if (html == null) {
                message.setText(text, false);
            } else {
                message.setText(text, html);
            }
        }
    });
}

From source file:uk.org.rbc1b.roms.scheduled.EmailScheduledService.java

/**
 * Generates and sends out emails./*from   w w w .ja  v  a2 s.c o m*/
 * @param email the email to send out
 * @throws MessagingException if problem with creating an email sender
 */
private void sendEmail(Email email) throws MessagingException {
    MimeMessage mimeMessage = this.mailGateway.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    if (email.getReplyTo() != null) {
        helper.setReplyTo(email.getReplyTo());
    }
    helper.setTo(email.getRecipient());
    if (email.getCc() != null) {
        helper.setCc(email.getCc());
    }
    helper.setSubject(email.getSubject());
    helper.setText(email.getText(), email.isHtml());
    this.mailGateway.send(mimeMessage);
}

From source file:com.exp.tracker.utils.EmailUtility.java

/**
 * Sends an email./*  w w w  . j  ava2  s  . c o  m*/
 * 
 * @param emailIdStrings
 *            A String array containing a list of email addresses.
 * @param emailSubject
 *            The subject of the email.
 * @param messageContent
 *            The message body.
 * @param emailAttachments
 *            A map containing any attachments. The key should be the file
 *            name. The value os a byte[] containing the binary
 *            representation of the attachment.
 * @throws EmailCommunicationException
 *             If any exception occurs.
 */
public void sendEmail(String[] emailIdStrings, String emailSubject, String messageContent,
        Map<String, byte[]> emailAttachments) throws EmailCommunicationException {
    if (null == emailIdStrings) {
        throw new EmailCommunicationException("Null array passed to this method.");
    }
    if (emailIdStrings.length == 0) {
        throw new EmailCommunicationException("No email addresses were provided. Array was empty.");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("About to send an email.");
    }

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

        helper.setFrom(fromAccount, fromName);
        InternetAddress[] toListArray = new InternetAddress[emailIdStrings.length];
        for (int i = 0; i < emailIdStrings.length; i++) {
            toListArray[i] = new InternetAddress(emailIdStrings[i]);
        }
        //To
        helper.setTo(toListArray);
        //Subject
        helper.setSubject(emailSubject);
        //Body
        helper.setText(messageContent, true);
        //Attachments
        if (null != emailAttachments) {
            Set<String> attachmentFileNames = emailAttachments.keySet();
            for (String fileName : attachmentFileNames) {
                helper.addAttachment(fileName,
                        new ByteArrayDataSource(emailAttachments.get(fileName), "application/octet-stream"));
            }
        }

        javaMailSender.send(mimeMessage);
        System.out.println("Mail sent successfully.");
    } catch (MessagingException e) {
        throw new EmailCommunicationException("Error sending email.", e);
    } catch (UnsupportedEncodingException e) {
        throw new EmailCommunicationException("Error sending email. Unsupported encoding.", e);
    }
}

From source file:org.opentides.eventhandler.EmailHandler.java

public void sendEmail(String[] to, String[] cc, String[] bcc, String replyTo, String subject, String body,
        File[] attachments) {//from w  w w.  ja v  a  2  s.  co  m
    try {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        mimeMessageHelper.setTo(toInetAddress(to));
        InternetAddress[] ccAddresses = toInetAddress(cc);
        if (ccAddresses != null)
            mimeMessageHelper.setCc(ccAddresses);
        InternetAddress[] bccAddresses = toInetAddress(bcc);
        if (bccAddresses != null)
            mimeMessageHelper.setBcc(bccAddresses);
        if (!StringUtil.isEmpty(replyTo))
            mimeMessageHelper.setReplyTo(replyTo);
        Map<String, Object> templateVariables = new HashMap<String, Object>();

        templateVariables.put("message-title", subject);
        templateVariables.put("message-body", body);

        StringWriter writer = new StringWriter();
        VelocityEngineUtils.mergeTemplate(velocityEngine, mailVmTemplate, "UTF-8", templateVariables, writer);

        mimeMessageHelper.setFrom(new InternetAddress(this.fromEmail, this.fromName));
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(writer.toString(), true);

        // check for attachment
        if (attachments != null && attachments.length > 0) {
            for (File attachment : attachments) {
                mimeMessageHelper.addAttachment(attachment.getName(), attachment);
            }
        }

        /**
         * The name of the identifier should be image
         * the number after the image name is the counter 
         * e.g. <img src="cid:image1" />
         */
        if (imagesPath != null && imagesPath.size() > 0) {
            int x = 1;
            for (String path : imagesPath) {
                FileSystemResource res = new FileSystemResource(new File(path));
                String imageName = "image" + x;
                mimeMessageHelper.addInline(imageName, res);
                x++;
            }
        }
        javaMailSender.send(mimeMessage);
    } catch (MessagingException e) {
        _log.error(e, e);
    } catch (UnsupportedEncodingException uee) {
        _log.error(uee, uee);
    }
}

From source file:com.pamarin.income.component.MailSenderImpl.java

@Override
public void send(MailCallback callback) {
    try {// w  w w.  j  a v  a  2  s  . com
        JavaMailSender sender = senderSetup();
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        callback.execute(helper);

        sender.send(message);
    } catch (Exception ex) {
        throw new UncheckedMailException(ex);
    }
}

From source file:thymeleafexamples.springmail.service.EmailService.java

public void sendSimpleMail(final String recipientName, final String recipientEmail, final Locale locale)
        throws MessagingException {

    // Prepare the evaluation context
    final Context ctx = new Context(locale);
    ctx.setVariable("name", recipientName);
    ctx.setVariable("subscriptionDate", new Date());
    ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
    message.setSubject("Example HTML email (simple)");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);//  w w  w  . j av a  2 s .c o m

    // Create the HTML body using Thymeleaf
    final String htmlContent = this.templateEngine.process("email-simple.html", ctx);
    message.setText(htmlContent, true /* isHtml */);

    // Send email
    this.mailSender.send(mimeMessage);

}

From source file:com.foilen.smalltools.email.EmailServiceSpring.java

@Override
public void sendTextEmail(String from, String to, String subject, String text) {

    try {//w w  w.ja  va  2 s. c om
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text, false);

        mailSender.send(message);
    } catch (Exception e) {
        throw new SmallToolsException("Could not send email", e);
    }
}