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, Resource resource) throws MessagingException 

Source Link

Document

Add an inline element to the MimeMessage, taking the content from a org.springframework.core.io.Resource .

Usage

From source file:com.rxx.common.util.MailUtil.java

/**
 * html/*from w w  w .  j a  v  a 2s .  c om*/
 *
 * @param host 
 * @param port
 * @param userName
 * @param password
 * @param title
 * @param contenthtml
 * @param imgs
 * @param toUser
 * @throws javax.mail.MessagingException
 */
public static void sendNews(String host, int port, String userName, String password, String title,
        String content, List<String> imgs, String[] toUser)
        throws MessagingException, javax.mail.MessagingException {
    JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
    // mail server
    senderImpl.setHost(host);

    // ,html
    MimeMessage mailMessage = senderImpl.createMimeMessage();
    // boolean,MimeMessageHelpertrue
    // multipart
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true);

    // 
    messageHelper.setTo(toUser);
    messageHelper.setFrom(userName);
    messageHelper.setSubject(title);
    // true HTML
    messageHelper.setText(content, true);

    int i = 0;
    for (String imagePath : imgs) {
        FileSystemResource img = new FileSystemResource(new File(imagePath));
        messageHelper.addInline(i + "", img);
        i++;
    }

    senderImpl.setUsername(userName); // ,username
    senderImpl.setPassword(password); // , password
    Properties prop = new Properties();
    prop.put("mail.smtp.auth", "true"); // true,
    prop.put("mail.smtp.timeout", "25000");
    senderImpl.setJavaMailProperties(prop);
    // 
    senderImpl.send(mailMessage);

    // 
    senderImpl.send(mailMessage);
}

From source file:com.epam.ta.reportportal.util.email.EmailService.java

/**
 * User creation confirmation email//from w  w w  .  j  av a2 s  .co m
 *
 * @param subject    Letter's subject
 * @param recipients Letter's recipients
 * @param url        ReportPortal URL
 */
public void sendConfirmationEmail(final String subject, final String[] recipients, final String url) {
    MimeMessagePreparator preparator = mimeMessage -> {
        URL logoImg = this.getClass().getClassLoader().getResource(LOGO);
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "utf-8");
        message.setSubject(subject);
        message.setTo(recipients);
        setFrom(message);

        Map<String, Object> email = new HashMap<>();
        email.put("url", url);
        String text = templateEngine.merge("registration-template.vm", email);
        message.setText(text, true);
        message.addInline("logoimg", new UrlResource(logoImg));
    };
    this.send(preparator);
}

From source file:com.epam.ta.reportportal.util.email.EmailService.java

/**
 * Restore password email// www. java 2s  .co m
 *
 * @param subject
 * @param recipients
 * @param url
 */
public void sendRestorePasswordEmail(final String subject, final String[] recipients, final String url,
        final String login) {
    MimeMessagePreparator preparator = mimeMessage -> {
        URL logoImg = this.getClass().getClassLoader().getResource(LOGO);
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "utf-8");
        message.setSubject(subject);
        message.setTo(recipients);

        setFrom(message);

        Map<String, Object> email = new HashMap<>();
        email.put("login", login);
        email.put("url", url);
        String text = templateEngine.merge("restore-password-template.vm", email);
        message.setText(text, true);
        message.addInline("logoimg", new UrlResource(logoImg));
    };
    this.send(preparator);
}

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

@Test
public void testSendMailWithInlineImage() throws MessagingException {
    // ?,???html//from  w w  w .ja  va 2 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:com.foilen.smalltools.email.EmailServiceSpring.java

@Override
public void sendEmail(EmailBuilder emailBuilder) {

    try {//from   w  w w  .j  av  a  2  s.c  o m
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(emailBuilder.getFrom());
        for (String to : emailBuilder.getTos()) {
            helper.addTo(to);
        }
        for (String cc : emailBuilder.getCcs()) {
            helper.addCc(cc);
        }
        for (String bcc : emailBuilder.getBccs()) {
            helper.addBcc(bcc);
        }
        helper.setSubject(emailBuilder.getSubject());
        helper.setText(emailBuilder.getBody(), emailBuilder.isHtml());

        // Inline
        for (EmailAttachment emailAttachment : emailBuilder.getInlineAttachments()) {
            helper.addInline(emailAttachment.getId(), emailAttachment.getResource());
        }

        // Attachment
        for (EmailAttachment emailAttachment : emailBuilder.getAttachments()) {
            helper.addAttachment(emailAttachment.getId(), emailAttachment.getResource());
        }

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

From source file:com.epam.ta.reportportal.util.email.EmailService.java

public void sendConfirmationEmail(CreateUserRQFull req, String basicUrl) {
    MimeMessagePreparator preparator = mimeMessage -> {
        URL logoImg = this.getClass().getClassLoader().getResource(LOGO);
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "utf-8");
        message.setSubject("Welcome to Report Portal");
        message.setTo(req.getEmail());//  w  ww .j av a 2  s . co m
        setFrom(message);

        Map<String, Object> email = new HashMap<>();
        email.put("url", basicUrl);
        email.put("login", normalizeUsername(req.getLogin()));
        email.put("password", req.getPassword());
        String text = templateEngine.merge("create-user-template.vm", email);
        message.setText(text, true);
        message.addInline("logoimg", new UrlResource(logoImg));
    };
    this.send(preparator);
}

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 av  a 2 s  .co  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:org.opentides.eventhandler.EmailHandler.java

public void sendEmail(String[] to, String[] cc, String[] bcc, String replyTo, String subject, String body,
        File[] attachments) {/*from www  .ja va 2s .  c o  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:org.jnap.core.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);
    if (acc.getFromName() != null) {
        helper.setFrom(acc.getFromEmailAddress(), acc.getFromName());
    } else {/*from ww  w. j a  va 2  s  . c o m*/
        this.setFrom(acc.getFromEmailAddress());
    }
    helper.setTo(getTo());
    if (getCc() != null) {
        helper.setCc(getCc());
    }
    if (getBcc() != null) {
        helper.setBcc(getBcc());
    }
    helper.setSentDate(new Date());
    mimeMessage.setSubject(getMessage(getSubject()), this.encoding);

    // sender info
    if (acc != null && StringUtils.isNotBlank(acc.getFromName())) {
        helper.setFrom(acc.getFromEmailAddress(), getMessage(acc.getFromName()));
    } else {
        helper.setFrom(acc.getFromEmailAddress());
    }
    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());
    }

    // set headers
    final Map<String, String> mailHeaders = this.getHeaders();
    for (String header : mailHeaders.keySet()) {
        mimeMessage.addHeader(header, mailHeaders.get(header));
    }

    // 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:net.triptech.metahive.service.EmailSenderService.java

/**
 * Send an email message using the configured Spring sender. On success
 * record the sent message in the datastore for reporting purposes
 *
 * @param email the email/*  w w w .jav a 2  s .co m*/
 * @param attachments the attachments
 * @throws ServiceException the service exception
 */
public final void send(final SimpleMailMessage email, TreeMap<String, Object> attachments)
        throws ServiceException {

    // Check to see whether the required fields are set (to, from, message)
    if (email.getTo() == null) {
        throw new ServiceException("Error sending email: Recipient " + "address required");
    }
    if (StringUtils.isBlank(email.getFrom())) {
        throw new ServiceException("Error sending email: Email requires " + "a from address");
    }
    if (StringUtils.isBlank(email.getText())) {
        throw new ServiceException("Error sending email: No email " + "message specified");
    }
    if (mailSender == null) {
        throw new ServiceException("The JavaMail sender has not " + "been configured");
    }

    // Prepare the email message
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = null;
    boolean htmlMessage = false;
    if (StringUtils.containsIgnoreCase(email.getText(), "<html")) {
        htmlMessage = true;
        try {
            helper = new MimeMessageHelper(message, true, "UTF-8");
        } catch (MessagingException me) {
            throw new ServiceException("Error preparing email for sending: " + me.getMessage());
        }
    } else {
        helper = new MimeMessageHelper(message);
    }

    try {
        helper.setTo(email.getTo());
        helper.setFrom(email.getFrom());
        helper.setSubject(email.getSubject());

        if (email.getCc() != null) {
            helper.setCc(email.getCc());
        }
        if (email.getBcc() != null) {
            helper.setBcc(email.getBcc());
        }

        if (htmlMessage) {
            String plainText = email.getText();
            try {
                ConvertHtmlToText htmlToText = new ConvertHtmlToText();
                plainText = htmlToText.convert(email.getText());
            } catch (Exception e) {
                logger.error("Error converting HTML to plain text: " + e.getMessage());
            }
            helper.setText(plainText, email.getText());
        } else {
            helper.setText(email.getText());
        }

        if (email.getSentDate() != null) {
            helper.setSentDate(email.getSentDate());
        } else {
            helper.setSentDate(Calendar.getInstance().getTime());
        }

    } catch (MessagingException me) {
        throw new ServiceException("Error preparing email for sending: " + me.getMessage());
    }

    // Append any attachments (if an HTML email)
    if (htmlMessage && attachments != null) {
        for (String id : attachments.keySet()) {
            Object reference = attachments.get(id);

            if (reference instanceof File) {
                try {
                    FileSystemResource res = new FileSystemResource((File) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    logger.error("Error appending File attachment: " + me.getMessage());
                }
            }
            if (reference instanceof URL) {
                try {
                    UrlResource res = new UrlResource((URL) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    logger.error("Error appending URL attachment: " + me.getMessage());
                }
            }
        }
    }

    // Send the email message
    try {
        mailSender.send(message);
    } catch (MailException me) {
        logger.error("Error sending email: " + me.getMessage());
        throw new ServiceException("Error sending email: " + me.getMessage());
    }
}