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

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

Introduction

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

Prototype

public void addInline(String contentId, InputStreamSource inputStreamSource, String contentType)
        throws MessagingException 

Source Link

Document

Add an inline element to the MimeMessage, taking the content from an org.springframework.core.InputStreamResource , and specifying the content type explicitly.

Usage

From source file:edu.mum.emailservice.EmailService.java

public void sendOrderReceivedMail(final String recipientName, final String recipientEmail, Order order,
        String documentName, final Locale locale) throws MessagingException {

    // Prepare the evaluation context
    final Context thymeContext = new Context(locale);
    thymeContext.setVariable("name", recipientName);
    thymeContext.setVariable("order", order);

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
    message.setSubject("Order Details");

    // could have CC, BCC, will also take an array of Strings
    message.setTo(recipientEmail);/*from   w  ww.  java  2  s  .c o  m*/

    // Create the HTML body using Thymeleaf
    final String htmlContent = this.templateEngine.process("orderReceivedMail", thymeContext);
    message.setText(htmlContent, true /* isHtml */);

    message.addInline("imtheguy", new ClassPathResource(IM_THE_GUY), JPG_MIME);

    String documentLocation = "templates/images/" + documentName;
    message.addAttachment(documentName, new ClassPathResource(documentLocation));

    /* 
       // Alternative
            File file = new File(documentLocation);
          message.addAttachment(documentName, file);
    */
    // Send email
    this.mailSender.send(mimeMessage);

}

From source file:edu.mum.eureka.email.EmailService.java

public void sendOrderReceivedMail(final String recipientName, final String recipientEmail, Order order,
        final Locale locale) throws MessagingException {

    // Prepare the evaluation context
    final Context thymeContext = new Context(locale);
    thymeContext.setVariable("name", recipientName);
    thymeContext.setVariable("order", order);

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
    message.setSubject("Your  Eureka Order Details");

    // could have CC, BCC, will also take an array of Strings
    message.setTo(recipientEmail);//from www . j  a  v  a  2  s  .c  o  m

    // Create the HTML body using Thymeleaf
    final String htmlContent = this.templateEngine.process("orderReceivedMail", thymeContext);
    message.setText(htmlContent, true);

    message.addInline("imtheguy", new ClassPathResource(IM_THE_GUY), JPG_MIME);

    /*String documentLocation = "templates/images/" + documentName ;
     message.addAttachment(documentName, new ClassPathResource(documentLocation));*/

    /*
      // Alternative
           File file = new File(documentLocation);
         message.addAttachment(documentName, file);
    */
    // Send email
    this.mailSender.send(mimeMessage);

}

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

public void sendMailWithInline(final String recipientName, final String recipientEmail,
        final String imageResourceName, final byte[] imageBytes, final String imageContentType,
        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"));
    ctx.setVariable("imageResourceName", imageResourceName); // so that we can reference it from HTML

    // 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 inline image");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);//from  w  ww. j  a v a  2  s. co m

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

    // Add the inline image, referenced from the HTML code as "cid:${imageResourceName}"
    final InputStreamSource imageSource = new ByteArrayResource(imageBytes);
    message.addInline(imageResourceName, imageSource, imageContentType);

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

}

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

@Async
public void sendMailWithInline(final String recipientName, final String recipientEmail,
        final String imageResourceName, final byte[] imageBytes, final String imageContentType,
        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"));
    ctx.setVariable("imageResourceName", imageResourceName); // so that we can reference it from HTML

    // 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 inline image");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);//from   ww  w  . j a  v a  2 s  . co  m

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

    // Add the inline image, referenced from the HTML code as "cid:${imageResourceName}"
    final InputStreamSource imageSource = new ByteArrayResource(imageBytes);
    message.addInline(imageResourceName, imageSource, imageContentType);

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

}

From source file:io.gravitee.management.service.impl.EmailServiceImpl.java

private String addResourcesInMessage(final MimeMessageHelper mailMessage, final String htmlText)
        throws Exception {
    final Document document = Jsoup.parse(htmlText);

    final List<String> resources = new ArrayList<>();

    final Elements imageElements = document.getElementsByTag("img");
    resources.addAll(/*w w  w.  ja va 2s  . c o  m*/
            imageElements.stream().filter(imageElement -> imageElement.hasAttr("src")).map(imageElement -> {
                final String src = imageElement.attr("src");
                imageElement.attr("src", "cid:" + src);
                return src;
            }).collect(Collectors.toList()));

    final String html = document.html();
    mailMessage.setText(html, true);

    for (final String res : resources) {
        final FileSystemResource templateResource = new FileSystemResource(new File(templatesPath, res));
        mailMessage.addInline(res, templateResource,
                MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(res));
    }

    return html;
}

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

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

    // 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 editable HTML email");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);//from w w w . ja  v  a 2 s  . c om

    // FIXME: duplicated images in src/main/resources and src/main/webapp
    // 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"));

    final StaticTemplateExecutor templateExecutor = new StaticTemplateExecutor(ctx, messageResolver,
            HTML5.getTemplateModeName());
    final String output = templateExecutor.processTemplateCode(htmlContent);
    message.setText(output, true /* isHtml */);

    // Add the inline images, referenced from the HTML code as "cid:image-name"
    message.addInline("background", new ClassPathResource(BACKGROUND_IMAGE), PNG_MIME);
    message.addInline("logo-background", new ClassPathResource(LOGO_BACKGROUND_IMAGE), PNG_MIME);
    message.addInline("thymeleaf-banner", new ClassPathResource(THYMELEAF_BANNER_IMAGE), PNG_MIME);
    message.addInline("thymeleaf-logo", new ClassPathResource(THYMELEAF_LOGO_IMAGE), PNG_MIME);

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

}

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

public String sendMailVLClassification(final String period, final String mailDate, final String protocolCode,
        final String recipientName, final String recipientAddress, final String recipientCity,
        final String recipientPhone, final String recipientEmail, final String practice_id,
        final String position, final String score, final String determinationCode,
        final String determinationDate, final String alboDate, final String expirationDate, final String phase,
        final String ef_period, final String ef_category, final String ef_tool, final String classificationUrl,
        final String respName, final String subject, final Locale locale, final MailImage logoImage,
        final MailImage footerImage, final int type) throws MessagingException {

    // Prepare the evaluation context
    final Context ctx = new Context(locale);
    ctx.setVariable("imagelogoMyweb", logoImage.getImageName());
    ctx.setVariable("mailDate", mailDate);
    ctx.setVariable("period", period);
    ctx.setVariable("protCode", protocolCode);
    ctx.setVariable("name", recipientName);
    ctx.setVariable("address", recipientAddress);
    ctx.setVariable("city", recipientCity);
    ctx.setVariable("phone", recipientPhone);
    ctx.setVariable("detCode", determinationCode);
    ctx.setVariable("detDate", determinationDate);
    ctx.setVariable("alboDate", alboDate);
    ctx.setVariable("expDate", expirationDate);
    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("classification_url", classificationUrl);
    ctx.setVariable("respName", respName);
    ctx.setVariable("subscriptionDate", new Date());
    //ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));
    ctx.setVariable("text", subject);
    ctx.setVariable("imagefooterVallag", footerImage.getImageName());

    // 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.setFrom("myweb-graduatoria@smartcommunitylab.it");
    message.setTo(recipientEmail);/*  ww w .j av a  2s . c  o m*/

    // Create the HTML body using Thymeleaf
    if (type == 1) {
        final String htmlContent = this.templateEngine.process("email-vallagarina.html", ctx);
        message.setText(htmlContent, true /* isHtml */);
    } else {
        final String htmlContent = this.templateEngine.process("email-vallagarina-final.html", ctx);
        message.setText(htmlContent, true /* isHtml */);
    }

    // Add the inline titles image, referenced from the HTML code as "cid:${imageResourceName}"
    final InputStreamSource imageLogo = new ByteArrayResource(logoImage.getImageByte());
    message.addInline(logoImage.getImageName(), imageLogo, logoImage.getImageType());

    // Add the inline footer image, referenced from the HTML code as "cid:${imageResourceName}"
    final InputStreamSource imageFooter = new ByteArrayResource(footerImage.getImageByte());
    message.addInline(footerImage.getImageName(), imageFooter, footerImage.getImageType());

    // 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:org.rill.bpm.common.mail.support.TemplateMailSenderSupport.java

@SuppressWarnings("unchecked")
protected MimeMessageHelper processMultipart(Map<String, Object> model, MimeMessageHelper messageHelper)
        throws MessagingException {

    // Handle multipart
    if (isMultipart(model)) {
        List<AttachmentWarper> list = new ArrayList<AttachmentWarper>();
        Object attachments = model.get(TemplateMailSender.ATTACHMENT_KEY);
        if (attachments.getClass().isArray()) {
            AttachmentWarper[] awArrays = ((AttachmentWarper[]) attachments);
            list.addAll(Arrays.asList(awArrays));
        } else if (attachments instanceof Collection) {
            Collection<AttachmentWarper> c = (Collection<AttachmentWarper>) attachments;
            list.addAll(c);/*from ww  w  .  j  a v  a2 s. c o m*/
        } else {
            list.add(((AttachmentWarper) attachments));
        }

        for (AttachmentWarper aw : list) {
            if (aw.getContentType() == null)
                messageHelper.addAttachment(aw.getAttachmentFileName(), aw.getInputStreamSource());
            else
                messageHelper.addAttachment(aw.getAttachmentFileName(), aw.getInputStreamSource(),
                        aw.getContentType());
        }
    }

    // Handle multipart
    if (isMultipart(model)) {
        List<AttachmentWarper> list = new ArrayList<AttachmentWarper>();
        Object inline = model.get(TemplateMailSender.INLINE_KEY);
        if (inline.getClass().isArray()) {
            AttachmentWarper[] awArrays = ((AttachmentWarper[]) inline);
            list.addAll(Arrays.asList(awArrays));
        } else if (inline instanceof Collection) {
            Collection<AttachmentWarper> c = (Collection<AttachmentWarper>) inline;
            list.addAll(c);
        } else {
            list.add(((AttachmentWarper) inline));
        }

        for (AttachmentWarper aw : list) {
            String cid = StringUtils.replace(aw.getAttachmentFileName(), ".", "_");
            if (aw.getContentType() == null)
                messageHelper.addInline(cid, aw.getInputStreamSource(),
                        messageHelper.getFileTypeMap().getContentType(aw.getAttachmentFileName()));
            else
                messageHelper.addInline(cid, aw.getInputStreamSource(), aw.getContentType());
        }
    }

    return messageHelper;
}

From source file:org.springframework.integration.samples.mailattachments.MimeMessageParsingTest.java

/**
 * This test will create a Mime Message that in return contains another
 * mime message. The nested mime message contains an attachment.
 *
 * The root message consist of both HTML and Text message.
 *
 *//*w ww.j  a  va  2  s. c  o  m*/
@Test
public void testProcessingOfNestedEmailAttachments() {

    final JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setPort(this.wiserPort);

    final MimeMessage rootMessage = mailSender.createMimeMessage();

    try {

        final MimeMessageHelper messageHelper = new MimeMessageHelper(rootMessage, true);

        messageHelper.setFrom("testfrom@springintegration.org");
        messageHelper.setTo("testto@springintegration.org");
        messageHelper.setSubject("Parsing of Attachments");
        messageHelper.setText("Spring Integration Rocks!", "Spring Integration <b>Rocks</b>!");

        final String pictureName = "picture.png";

        final ByteArrayResource byteArrayResource = getFileData(pictureName);

        messageHelper.addInline("picture12345", byteArrayResource, "image/png");

    } catch (MessagingException e) {
        throw new MailParseException(e);
    }

    mailSender.send(rootMessage);

    final List<WiserMessage> wiserMessages = wiser.getMessages();

    Assert.assertTrue(wiserMessages.size() == 1);

    boolean foundTextMessage = false;
    boolean foundPicture = false;
    boolean foundHtmlMessage = false;

    for (WiserMessage wiserMessage : wiserMessages) {

        List<EmailFragment> emailFragments = new ArrayList<EmailFragment>();

        try {

            final MimeMessage mailMessage = wiserMessage.getMimeMessage();
            EmailParserUtils.handleMessage(null, mailMessage, emailFragments);

        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving Mime Message.");
        }

        Assert.assertTrue(emailFragments.size() == 3);

        for (EmailFragment emailFragment : emailFragments) {
            if ("<picture12345>".equals(emailFragment.getFilename())) {
                foundPicture = true;
            }

            if ("message.txt".equals(emailFragment.getFilename())) {
                foundTextMessage = true;
            }

            if ("message.html".equals(emailFragment.getFilename())) {
                foundHtmlMessage = true;
            }
        }

        Assert.assertTrue(foundPicture);
        Assert.assertTrue(foundTextMessage);
        Assert.assertTrue(foundHtmlMessage);

    }
}