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

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

Introduction

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

Prototype

public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource, String contentType)
        throws MessagingException 

Source Link

Document

Add an attachment to the MimeMessage, taking the content from an org.springframework.core.io.InputStreamResource .

Usage

From source file:eu.openanalytics.rsb.component.EmailDepositHandlerTestCase.java

@Test
public void handleJob() throws Exception {
    final MimeMessage mimeMessage = new MimeMessage((Session) null);
    final MimeMessageHelper mmh = new MimeMessageHelper(mimeMessage, true);
    mmh.setReplyTo("test@test.com");
    mmh.setText("test job");
    mmh.addAttachment("r-job-sample.zip", new ClassPathResource("data/r-job-sample.zip"),
            Constants.ZIP_CONTENT_TYPE);

    final DepositEmailConfiguration depositEmailConfiguration = mock(PersistedDepositEmailConfiguration.class);
    when(depositEmailConfiguration.getApplicationName()).thenReturn(TEST_APPLICATION_NAME);
    final Message<MimeMessage> message = MessageBuilder.withPayload(mimeMessage)
            .setHeader(EmailDepositHandler.EMAIL_CONFIG_HEADER_NAME, depositEmailConfiguration).build();

    emailDepositHandler.handleJob(message);

    final ArgumentCaptor<MultiFilesJob> jobCaptor = ArgumentCaptor.forClass(MultiFilesJob.class);
    verify(messageDispatcher).dispatch(jobCaptor.capture());

    final MultiFilesJob job = jobCaptor.getValue();
    assertThat(job.getApplicationName(), is(TEST_APPLICATION_NAME));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_SUBJECT_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_ADDRESSEE_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_REPLY_TO_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_REPLY_CC_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_BODY_META_NAME), is(true));
    assertThat(job.getSource(), is(Source.EMAIL));
    job.destroy();/*from  w  ww.ja v a 2 s. c o m*/
}

From source file:com.aurora.mail.service.MailService.java

/**
 * @param to//from w w w.  j a  v  a2s.c o m
 * @param subject
 * @param content
 * @param isMultipart
 * @param isHtml
 */
@Async
public void sendEmailWithAttachment(String to, String subject, String content, final String attachmentFileName,
        final byte[] attachmentBytes, final String attachmentContentType, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail to user '{}'!", to);

    final InputStreamSource attachmentSource = new ByteArrayResource(attachmentBytes);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(from);
        message.setSubject(subject);
        message.setText(content, isHtml);

        // Add the attachment
        message.addAttachment(attachmentFileName, attachmentSource, attachmentContentType);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'!", to);
    } catch (Exception e) {
        log.error("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}

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

public void sendMailWithAttachment(final String recipientName, final String recipientEmail,
        final String attachmentFileName, final byte[] attachmentBytes, final String attachmentContentType,
        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, true /* multipart */, "UTF-8");
    message.setSubject("Example HTML email with attachment");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);//from w  ww.  j a v a 2 s  . c  o m

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

    // Add the attachment
    final InputStreamSource attachmentSource = new ByteArrayResource(attachmentBytes);
    message.addAttachment(attachmentFileName, attachmentSource, attachmentContentType);

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

}

From source file:gr.abiss.calipso.service.EmailService.java

@Async
public void sendMailWithAttachment(final String recipientName, final String recipientEmail,
        final String attachmentFileName, final byte[] attachmentBytes, final String attachmentContentType,
        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, true /* multipart */, "UTF-8");
    message.setSubject("Example HTML email with attachment");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);/*w  ww .  j av  a  2  s.  c o m*/

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

    // Add the attachment
    final InputStreamSource attachmentSource = new ByteArrayResource(attachmentBytes);
    message.addAttachment(attachmentFileName, attachmentSource, attachmentContentType);

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

}

From source file:eu.trentorise.smartcampus.citizenportal.service.EmailService.java

public String sendMailWithAttachment(final String recipientName, final String recipientEmail,
        final String practice_id, final String position, final String score, final String phase,
        final String ef_period, final String ef_category, final String ef_tool, final String subject,
        final String attachmentFileName, final byte[] attachmentBytes, final String attachmentContentType,
        final Locale locale) throws MessagingException {

    // Prepare the evaluation context
    final Context ctx = new Context(locale);
    ctx.setVariable("name", recipientName);
    ctx.setVariable("practice_id", practice_id);
    ctx.setVariable("position", position);
    ctx.setVariable("score", score);
    ctx.setVariable("phase", phase);
    ctx.setVariable("ef_period", ef_period);
    ctx.setVariable("ef_category", ef_category);
    ctx.setVariable("ef_tool", ef_tool);
    ctx.setVariable("subscriptionDate", new Date());
    //ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));
    ctx.setVariable("text", subject);

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8");
    message.setSubject("Graduatoria Edilizia Abitativa");
    //message.setFrom("thymeleaf@example.com");
    message.setFrom("myweb.edilizia@comunitadellavallagarina.tn.it");
    message.setTo(recipientEmail);/*from   w w w. jav  a 2s  .c o m*/

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

    // Add the attachment
    final InputStreamSource attachmentSource = new ByteArrayResource(attachmentBytes);
    message.addAttachment(attachmentFileName, attachmentSource, attachmentContentType);

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

    return recipientName + "OK";
}

From source file:it.ozimov.springboot.templating.mail.utils.EmailToMimeMessage.java

@Override
public MimeMessage apply(final Email email) {
    final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    final MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,
            fromNullable(email.getEncoding()).or(Charset.forName("UTF-8")).displayName());

    try {//from   ww  w . j av a2  s .c  om
        messageHelper.setFrom(email.getFrom());
        if (ofNullable(email.getReplyTo()).isPresent()) {
            messageHelper.setReplyTo(email.getReplyTo());
        }
        if (ofNullable(email.getTo()).isPresent()) {
            for (final InternetAddress address : email.getTo()) {
                messageHelper.addTo(address);
            }
        }
        if (ofNullable(email.getCc()).isPresent()) {
            for (final InternetAddress address : email.getCc()) {
                messageHelper.addCc(address);
            }
        }
        if (ofNullable(email.getBcc()).isPresent()) {
            for (final InternetAddress address : email.getBcc()) {
                messageHelper.addBcc(address);
            }
        }
        if (ofNullable(email.getAttachments()).isPresent()) {
            for (final EmailAttachmentImpl attachment : email.getAttachments()) {
                try {
                    messageHelper.addAttachment(attachment.getAttachmentName(), attachment.getInputStream(),
                            attachment.getContentType().getType());
                } catch (IOException e) {
                    log.error("Error while converting Email to MimeMessage");
                    throw new EmailConversionException(e);
                }
            }
        }
        messageHelper.setSubject(ofNullable(email.getSubject()).orElse(""));
        messageHelper.setText(ofNullable(email.getBody()).orElse(""));

        if (nonNull(email.getSentAt())) {
            messageHelper.setSentDate(email.getSentAt());
        }
    } catch (MessagingException e) {
        log.error("Error while converting Email to MimeMessage");
        throw new EmailConversionException(e);
    }

    return mimeMessage;
}

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) {/*w w  w. jav  a  2 s. co  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: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;
        }//  w  w  w  .  j  a  va  2s .  co  m

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

From source file:org.kuali.kra.service.impl.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) {
    JavaMailSender sender = createSender();

    if (sender != null) {
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = null;

        try {/*from  w w  w .j a  v a2  s .c  om*/
            helper = new MimeMessageHelper(message, true, DEFAULT_ENCODING);
            helper.setFrom(from);

            if (CollectionUtils.isNotEmpty(toAddresses)) {
                for (String toAddress : toAddresses) {
                    helper.addTo(toAddress);
                }
            }

            if (StringUtils.isNotBlank(subject)) {
                helper.setSubject(subject);
            } else {
                LOG.warn("Sending message with empty subject.");
            }

            helper.setText(body, htmlMessage);

            if (CollectionUtils.isNotEmpty(ccAddresses)) {
                for (String ccAddress : ccAddresses) {
                    helper.addCc(ccAddress);
                }
            }

            if (CollectionUtils.isNotEmpty(bccAddresses)) {
                for (String bccAddress : bccAddresses) {
                    helper.addBcc(bccAddress);
                }
            }

            if (CollectionUtils.isNotEmpty(attachments)) {
                for (EmailAttachment attachment : attachments) {
                    helper.addAttachment(attachment.getFileName(),
                            new ByteArrayResource(attachment.getContents()), attachment.getMimeType());
                }
            }

            sender.send(message);
        } catch (MessagingException ex) {
            LOG.error("Failed to create mime message helper.", ex);
        } catch (Exception e) {
            LOG.error("Failed to send email.", e);
        }
    } else {
        LOG.info(
                "Failed to send email due to inability to obtain valid email sender, please check your configuration.");
    }
}

From source file:org.openvpms.web.component.error.ErrorReporter.java

/**
 * Reports an error./*from  w  w  w  .  j a va 2 s  .c o m*/
 *
 * @param report  the error report
 * @param replyTo the reply-to email address. May be {@code null}
 */
public void report(final ErrorReport report, String replyTo) {
    try {
        JavaMailSender sender = ServiceHelper.getMailSender();
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        String subject = report.getVersion() + ": " + report.getMessage();
        helper.setSubject(subject);
        helper.setFrom(from);
        helper.setTo(to);
        if (!StringUtils.isEmpty(replyTo)) {
            helper.setReplyTo(replyTo);
        }
        String text = getText(report);
        if (text != null) {
            helper.setText(text);
        }
        InputStreamSource source = new InputStreamSource() {
            public InputStream getInputStream() {
                return new ByteArrayInputStream(report.toXML().getBytes());
            }
        };
        helper.addAttachment("error-report.xml", source, DocFormats.XML_TYPE);
        sender.send(message);
    } catch (Throwable exception) {
        log.error(exception, exception);
        ErrorDialog.show(Messages.get("errorreportdialog.senderror"));
    }
}