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, @Nullable String encoding)
        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: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  . ja  v a2  s . com*/

    // 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:org.topazproject.ambra.email.impl.FreemarkerTemplateMailer.java

/**
 * Mail the email formatted using the given templates
 * @param toEmailAddresses List of email addresses to which emails should be sent.  White space delimited.
 * @param fromEmailAddress fromEmailAddress
 * @param subject subject of the email//from  w  w w. ja v a2s. c  o m
 * @param context context to set the values from for the template
 * @param textTemplateFilename textTemplateFilename
 * @param htmlTemplateFilename htmlTemplateFilename
 */
public void mail(final String toEmailAddresses, final String fromEmailAddress, final String subject,
        final Map<String, Object> context, final String textTemplateFilename,
        final String htmlTemplateFilename) {
    final StringTokenizer emailTokens = new StringTokenizer(toEmailAddresses);

    while (emailTokens.hasMoreTokens()) {
        final String toEmailAddress = emailTokens.nextToken();
        final MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(final MimeMessage mimeMessage) throws MessagingException, IOException {
                final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true,
                        configuration.getDefaultEncoding());
                message.setTo(new InternetAddress(toEmailAddress));
                message.setFrom(new InternetAddress(fromEmailAddress, (String) context.get(USER_NAME_KEY)));
                message.setSubject(subject);

                // Create a "text" Multipart message
                final Multipart mp = createPartForMultipart(textTemplateFilename, context, "alternative",
                        MIME_TYPE_TEXT_PLAIN + "; charset=" + configuration.getDefaultEncoding());

                // Create a "HTML" Multipart message
                final Multipart htmlContent = createPartForMultipart(htmlTemplateFilename, context, "related",
                        MIME_TYPE_TEXT_HTML + "; charset=" + configuration.getDefaultEncoding());

                final BodyPart htmlPart = new MimeBodyPart();
                htmlPart.setContent(htmlContent);
                mp.addBodyPart(htmlPart);

                mimeMessage.setContent(mp);
            }
        };
        mailSender.send(preparator);
        if (log.isDebugEnabled()) {
            log.debug("Mail sent to:" + toEmailAddress);
        }
    }
}

From source file:com.mobileman.projecth.business.impl.MailManagerImpl.java

/** 
 * {@inheritDoc}/*from www  . j a va 2s .c om*/
 * @see com.mobileman.projecth.business.MailManager#sendActivationEmail(User, String)
 */
@Override
public void sendActivationEmail(final User user, final String serverDnsName) {
    if (log.isDebugEnabled()) {
        log.debug("sendActivationEmail(" + user + ", " + serverDnsName + ") - start");
    }

    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        /**
         * {@inheritDoc}
         * @see org.springframework.mail.javamail.MimeMessagePreparator#prepare(javax.mail.internet.MimeMessage)
         */
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            if (log.isDebugEnabled()) {
                log.debug("$MimeMessagePreparator.prepare(MimeMessage) - start"); //$NON-NLS-1$
            }

            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, EMAIL_ENCODING);
            messageHelper.setSentDate(new Date());
            messageHelper.setTo(user.getUserAccount().getEmail());
            messageHelper.setFrom("mitglied@projecth.com");
            messageHelper.setSubject("Ihre Anmeldung bei projecth");

            String tmpServerDnsName = serverDnsName;
            if (tmpServerDnsName == null || tmpServerDnsName.trim().length() == 0) {
                tmpServerDnsName = "projecth.de";
            }

            Map<String, Object> model = new HashMap<String, Object>();
            model.put("user", user);
            model.put("dns_server_name", tmpServerDnsName);

            String htmlMessage = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "sign-up-activation-email-body.vm", model);
            String textMessage = HTMLTextParser.htmlToText(htmlMessage);
            messageHelper.setText(textMessage, htmlMessage);

            if (log.isDebugEnabled()) {
                log.debug("$MimeMessagePreparator.prepare(MimeMessage) - returns"); //$NON-NLS-1$
            }
        }
    };

    this.mailSender.send(preparator);

    if (log.isDebugEnabled()) {
        log.debug("sendActivationEmail(User) - returns"); //$NON-NLS-1$
    }
}

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);/*  ww  w  . j  a v  a2 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);

    return recipientName + "OK";
}

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

/**
 * Finish launch notification/*from  w  ww. j a va2s  . c om*/
 *
 * @param recipients List of recipients
 * @param url        ReportPortal URL
 * @param launch     Launch
 */
public void sendLaunchFinishNotification(final String[] recipients, final String url, final Launch launch,
        final Project.Configuration settings) {
    String subject = String.format(FINISH_LAUNCH_EMAIL_SUBJECT, launch.getName(), launch.getNumber());
    MimeMessagePreparator preparator = mimeMessage -> {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "utf-8");
        message.setSubject(subject);
        message.setTo(recipients);
        setFrom(message);

        Map<String, Object> email = new HashMap<>();
        /* Email fields values */
        email.put("name", launch.getName());
        email.put("number", String.valueOf(launch.getNumber()));
        email.put("description", launch.getDescription());
        email.put("url", url);

        /* Launch execution statistics */
        email.put("total", launch.getStatistics().getExecutionCounter().getTotal().toString());
        email.put("passed", launch.getStatistics().getExecutionCounter().getPassed().toString());
        email.put("failed", launch.getStatistics().getExecutionCounter().getFailed().toString());
        email.put("skipped", launch.getStatistics().getExecutionCounter().getSkipped().toString());

        /* Launch issue statistics global counters */
        email.put("productBugTotal", launch.getStatistics().getIssueCounter().getProductBugTotal().toString());
        email.put("automationBugTotal",
                launch.getStatistics().getIssueCounter().getAutomationBugTotal().toString());
        email.put("systemIssueTotal",
                launch.getStatistics().getIssueCounter().getSystemIssueTotal().toString());
        email.put("noDefectTotal", launch.getStatistics().getIssueCounter().getNoDefectTotal().toString());
        email.put("toInvestigateTotal",
                launch.getStatistics().getIssueCounter().getToInvestigateTotal().toString());

        /* Launch issue statistics custom sub-types */
        if (launch.getStatistics().getIssueCounter().getProductBug().entrySet().size() > 1) {
            Map<StatisticSubType, String> pb = new LinkedHashMap<>();
            launch.getStatistics().getIssueCounter().getProductBug().forEach((k, v) -> {
                if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL))
                    pb.put(settings.getByLocator(k), v.toString());
            });
            email.put("pbInfo", pb);
        }
        if (launch.getStatistics().getIssueCounter().getAutomationBug().entrySet().size() > 1) {
            Map<StatisticSubType, String> ab = new LinkedHashMap<>();
            launch.getStatistics().getIssueCounter().getAutomationBug().forEach((k, v) -> {
                if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL))
                    ab.put(settings.getByLocator(k), v.toString());
            });
            email.put("abInfo", ab);
        }
        if (launch.getStatistics().getIssueCounter().getSystemIssue().entrySet().size() > 1) {
            Map<StatisticSubType, String> si = new LinkedHashMap<>();
            launch.getStatistics().getIssueCounter().getSystemIssue().forEach((k, v) -> {
                if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL))
                    si.put(settings.getByLocator(k), v.toString());
            });
            email.put("siInfo", si);
        }
        if (launch.getStatistics().getIssueCounter().getNoDefect().entrySet().size() > 1) {
            Map<StatisticSubType, String> nd = new LinkedHashMap<>();
            launch.getStatistics().getIssueCounter().getNoDefect().forEach((k, v) -> {
                if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL))
                    nd.put(settings.getByLocator(k), v.toString());
            });
            email.put("ndInfo", nd);
        }
        if (launch.getStatistics().getIssueCounter().getToInvestigate().entrySet().size() > 1) {
            Map<StatisticSubType, String> ti = new LinkedHashMap<>();
            launch.getStatistics().getIssueCounter().getToInvestigate().forEach((k, v) -> {
                if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL))
                    ti.put(settings.getByLocator(k), v.toString());
            });
            email.put("tiInfo", ti);
        }

        String text = templateEngine.merge("finish-launch-template.vm", email);
        message.setText(text, true);
        message.addInline("logoimg", new UrlResource(getClass().getClassLoader().getResource(LOGO)));
    };
    this.send(preparator);
}

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

/**
 * @param to/*from   ww  w. j ava2s .  co  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:com.gcrm.util.mail.MailService.java

public void sendHtmlMail(String from, String[] to, String subject, String text, String[] fileNames,
        File[] files) throws Exception {
    List<EmailSetting> emailSettings = baseService.getAllObjects(EmailSetting.class.getSimpleName());
    EmailSetting emailSetting = null;//ww w .j  a v  a  2s.  c  om
    if (emailSettings != null && emailSettings.size() > 0) {
        emailSetting = emailSettings.get(0);
    } else {
        return;
    }
    if (from == null) {
        from = emailSetting.getFrom_address();
    }
    Session mailSession = createSmtpSession(emailSetting);

    if (mailSession != null) {
        Transport transport = mailSession.getTransport();
        MimeMessage msg = new MimeMessage(mailSession);
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text, true);
        if (fileNames != null && files != null) {
            String fileName = null;
            File file = null;
            for (int i = 0; i < fileNames.length; i++) {
                fileName = fileNames[i];
                file = files[i];
                if (fileName != null && file != null) {
                    helper.addAttachment(fileName, file);
                }
            }
        }
        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
    }

}

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

@Test
public void testSendMailWithAttachedImage() throws MessagingException {
    // ?,???html//w  w w  .  j  av  a  2 s .  c om
    MimeMessage mailMessage = senderImpl.createMimeMessage();
    // ?boolean,?MimeMessageHelpertrue?
    // multipart? true?? ?html?
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

    // 
    messageHelper.setTo("29283212@qq.com");
    messageHelper.setFrom("29283212@qq.com");
    messageHelper.setSubject("!?");
    // true ?HTML?
    messageHelper.setText(
            "<html><head></head><body><h1>?</h1></body></html>", true);

    FileSystemResource file = new FileSystemResource(new File(imagePath));
    // ???
    messageHelper.addAttachment("image", file);

    // ??
    senderImpl.send(mailMessage);

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

From source file:com.github.dactiv.common.spring.mail.JavaMailService.java

/**
 * ??//w ww  .j a  v a2  s . co m
 * 
 * @param sendTo ??
 * @param sendFrom ?
 * @param subject 
 * @param content 
 * @param attachment mapkey????value?????
 */
private void doSend(String sendTo, String sendFrom, String subject, String content,
        Map<String, File> attachment) {
    try {
        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, encoding);

        helper.setTo(sendTo);
        helper.setFrom(sendFrom);
        helper.setSubject(subject);
        helper.setText(content, true);

        if (!MapUtils.isEmpty(attachment)) {
            for (Entry<String, File> entry : attachment.entrySet()) {
                helper.addAttachment(entry.getKey(), entry.getValue());
            }
        }

        mailSender.send(msg);
        logger.info("???");
    } catch (MessagingException e) {
        logger.error("", e);
    } catch (Exception e) {
        logger.error("??", e);
    }
}

From source file:com.enonic.cms.core.mail.AbstractSendMailService.java

private MimeMessageHelper createMessage(MessageSettings settings, boolean multipart) throws Exception {
    final MimeMessageHelper message = new MimeMessageHelper(this.mailSender.createMimeMessage(), multipart,
            MAIL_ENCODING);/* w w  w .  j  a  v a 2s  .com*/
    message.setFrom(settings.getFromMail(), settings.getFromName());
    return message;
}