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

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

Introduction

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

Prototype

public void setTo(String[] to) throws MessagingException 

Source Link

Usage

From source file:com.gst.infrastructure.reportmailingjob.service.ReportMailingJobEmailServiceImpl.java

@Override
public void sendEmailWithAttachment(ReportMailingJobEmailData reportMailingJobEmailData) {
    try {//  w  w  w . jav a 2s. com
        // get all ReportMailingJobConfiguration objects from the database
        this.reportMailingJobConfigurationDataCollection = this.reportMailingJobConfigurationReadPlatformService
                .retrieveAllReportMailingJobConfigurations();

        JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
        javaMailSenderImpl.setHost(this.getGmailSmtpServer());
        javaMailSenderImpl.setPort(this.getGmailSmtpPort());
        javaMailSenderImpl.setUsername(this.getGmailSmtpUsername());
        javaMailSenderImpl.setPassword(this.getGmailSmtpPassword());
        javaMailSenderImpl.setJavaMailProperties(this.getJavaMailProperties());

        MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

        mimeMessageHelper.setTo(reportMailingJobEmailData.getTo());
        mimeMessageHelper.setText(reportMailingJobEmailData.getText());
        mimeMessageHelper.setSubject(reportMailingJobEmailData.getSubject());

        if (reportMailingJobEmailData.getAttachment() != null) {
            mimeMessageHelper.addAttachment(reportMailingJobEmailData.getAttachment().getName(),
                    reportMailingJobEmailData.getAttachment());
        }

        javaMailSenderImpl.send(mimeMessage);
    }

    catch (MessagingException e) {
        // handle the exception
        e.printStackTrace();
    }
}

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

/**
 * ??//from  www  .jav  a 2s  .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:org.jrecruiter.service.notification.impl.NotificationServiceActivator.java

/** {@inheritDoc} */
public void sendEmail(final EmailRequest request) {

    final MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException, IOException {

            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            message.setFrom("no_reply@jrecruiter.org");
            message.setTo(request.getEmail());
            message.setSubject(request.getSubject());

            final Locale locale = LocaleContextHolder.getLocale();

            final Template textTemplate = freemarkerConfiguration
                    .getTemplate(request.getTemplatePrefix() + "-text.ftl", locale);

            final StringWriter textWriter = new StringWriter();
            try {
                textTemplate.process(request.getContext(), textWriter);
            } catch (TemplateException e) {
                throw new MailPreparationException("Can't generate email body.", e);
            }/*  ww  w . java2s . c  o  m*/

            final Template htmlTemplate = freemarkerConfiguration
                    .getTemplate(request.getTemplatePrefix() + "-html.ftl", locale);

            final StringWriter htmlWriter = new StringWriter();
            try {
                htmlTemplate.process(request.getContext(), htmlWriter);
            } catch (TemplateException e) {
                throw new MailPreparationException("Can't generate email body.", e);
            }

            message.setText(textWriter.toString(), htmlWriter.toString());

        }
    };

    mailSender.send(preparator);
}

From source file:com.globocom.grou.report.ReportService.java

private void notifyByMail(Test test, String email, Map<String, Double> result) throws Exception {
    MimeMessagePreparator messagePreparator = mimeMessage -> {
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setTo(email);
        messageHelper.setFrom(MAIL_FROM);
        messageHelper.setSubject(getSubject(test));
        Context context = new Context();
        context.setVariable("project", test.getProject());
        context.setVariable("name", test.getName());
        HashMap<String, Object> testContext = new HashMap<>();
        testContext.put("dashboard", test.getDashboard());
        testContext.put("loaders", test.getLoaders().stream().map(Loader::getName).collect(Collectors.toSet()));
        testContext.put("properties", test.getProperties());
        testContext.put("id", test.getId());
        testContext.put("created", test.getCreatedDate().toString());
        testContext.put("lastModified", test.getLastModifiedDate().toString());
        testContext.put("durationTimeMillis", test.getDurationTimeMillis());
        context.setVariable("testContext", mapper.writeValueAsString(testContext).split("\\R"));
        Set<String> tags = test.getTags();
        context.setVariable("tags", tags);
        context.setVariable("metrics", new TreeMap<>(result));
        String content = templateEngine.process("reportEmail", context);
        messageHelper.setText(content, true);
    };/*  www . ja v a 2  s  . com*/
    try {
        emailSender.send(messagePreparator);
        LOGGER.info(
                "Test " + test.getProject() + "." + test.getName() + ": sent notification to email " + email);
    } catch (MailException e) {
        LOGGER.error(e.getMessage(), e);
    }
}

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

@Test
public void testSendMailWithAttachedImage() throws MessagingException {
    // ?,???html/*from   w  w  w  .j  av  a2  s .c o  m*/
    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: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. j a  v a  2s  . c  om
    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.edgenius.core.service.impl.MailEngineService.java

public void sendHtmlMail(final SimpleMailMessage msg, final String templateName, final Map model) {
    final String content = generateContent(templateName, model);

    final String subject = generateContent(getSubjectName(templateName), model);
    try {//from  ww  w.ja  va 2 s.c  o m
        mailSender.send(new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMsg) throws Exception {
                MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true, "utf-8");
                helper.setTo(msg.getTo());
                helper.setFrom(msg.getFrom());
                if (msg.getBcc() != null)
                    helper.setBcc(msg.getBcc());
                if (!StringUtils.isBlank(subject))
                    helper.setSubject(subject);
                else
                    helper.setSubject(msg.getSubject());
                helper.setText(content, true);
            }

        });
    } catch (Exception e) {
        log.error("Send HTML mail failed on {}", e.toString(), e);
        log.info("Message subject: {}", subject);
        log.info("Message content: {}", content);
    }
}

From source file:gov.nih.nci.cabig.caaers.tools.mail.CaaersJavaMailSender.java

/**
 * This method is used to send an email//ww w  .  ja va2  s  .  com
 */
public void sendMail(String[] to, String[] cc, String subject, String content, String[] attachmentFilePaths) {
    if (to == null || to.length == 0 || to[0] == null) {
        return;
    }
    try {
        MimeMessage message = createMimeMessage();
        message.setSubject(subject);

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        if (cc != null && cc.length > 0) {
            helper.setCc(cc);
        }
        helper.setText(content);

        for (String attachmentPath : attachmentFilePaths) {
            if (StringUtils.isNotEmpty(attachmentPath)) {
                File f = new File(attachmentPath);
                FileSystemResource file = new FileSystemResource(f);
                helper.addAttachment(file.getFilename(), file);
            }
        }
        send(message);

    } catch (Exception e) {
        if (SUPRESS_MAIL_SEND_EXCEPTION)
            return; //supress the excetion related to email sending
        throw new CaaersSystemException("Error while sending email to " + to[0], e);
    }
}

From source file:jedai.business.JRegistrationService.java

/**
 * @param user//from w  w  w  .j a v a  2 s  .c o  m
 */
protected void sendRequestPasswordEmail(final Users user) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo("dominick@infrared5.com");
            message.setFrom("daccattato@infrared5.com"); // could be parameterized...
            Map<String, Users> model = new HashMap<String, Users>();
            model.put("user", user);
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "request-password.vm",
                    model);
            message.setText(text, true);
        }
    };
    this.mailSender.send(preparator);
}

From source file:jedai.business.JRegistrationService.java

/**
 * @param user//  ww  w  .  j  ava  2  s. com
 */
protected void sendConfirmationEmail(final Users user) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo("dominick@infrared5.com");
            message.setFrom("daccattato@infrared5.com"); // could be parameterized...
            Map<String, Users> model = new HashMap<String, Users>();
            model.put("user", user);
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "registration-confirmation.vm", model);
            message.setText(text, true);
        }
    };
    this.mailSender.send(preparator);
}