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:de.whs.poodle.services.EmailService.java

public void sendMail(Instructor from, String toUsername, List<String> bccUsernames, boolean senderBcc,
        String subject, String text, boolean setNoReply) throws MessagingException {
    if (bccUsernames == null)
        bccUsernames = new ArrayList<>();

    if (toUsername == null && bccUsernames.isEmpty()) {
        log.info("sendMail(): no recipients, aborting.");
        return;/*from  w ww. j  a  v a2 s .  c om*/
    }

    // may be empty if bccUsernames was not specified
    List<String> bccEmails = getEmailsForUsernames(bccUsernames);

    String fromEmail = getEmailForUsername(from.getUsername());

    // create "from" as "FirstName LastName <email@w-hs.de>"
    String fromStr = String.format("%s %s <%s>", from.getFirstName(), from.getLastName(), fromEmail);

    if (senderBcc)
        bccEmails.add(fromEmail);

    // create MimeMessage
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8");

    helper.setSubject("[Poodle] " + subject);
    helper.setFrom(fromStr);

    if (toUsername != null) {
        String toEmail = getEmailForUsername(toUsername);
        helper.setTo(toEmail);
    }

    if (!bccEmails.isEmpty())
        helper.setBcc(bccEmails.toArray(new String[0]));

    if (setNoReply)
        helper.setReplyTo(poodle.getEmailNoReplyAddress());

    helper.setText(text);

    mailSender.send(mimeMessage);
}

From source file:net.groupbuy.service.impl.MailServiceImpl.java

public void send(String smtpFromMail, String smtpHost, Integer smtpPort, String smtpUsername,
        String smtpPassword, String toMail, String subject, String templatePath, Map<String, Object> model,
        boolean async) {
    Assert.hasText(smtpFromMail);/*w  w  w  .  ja  v  a  2 s .  co m*/
    Assert.hasText(smtpHost);
    Assert.notNull(smtpPort);
    Assert.hasText(smtpUsername);
    Assert.hasText(smtpPassword);
    Assert.hasText(toMail);
    Assert.hasText(subject);
    Assert.hasText(templatePath);
    try {
        Setting setting = SettingUtils.get();
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = configuration.getTemplate(templatePath);
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
        javaMailSender.setHost(smtpHost);
        javaMailSender.setPort(smtpPort);
        javaMailSender.setUsername(smtpUsername);
        javaMailSender.setPassword(smtpPassword);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "utf-8");
        mimeMessageHelper.setFrom(MimeUtility.encodeWord(setting.getSiteName()) + " <" + smtpFromMail + ">");
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setTo(toMail);
        mimeMessageHelper.setText(text, true);
        if (async) {
            addSendTask(mimeMessage);
        } else {
            javaMailSender.send(mimeMessage);
        }
    } catch (TemplateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

From source file:mx.edu.um.mateo.rh.web.JefeSeccionController.java

private void enviaCorreo(String tipo, List<JefeSeccion> jefeSeccions, HttpServletRequest request)
        throws JRException, MessagingException {
    log.debug("Enviando correo {}", tipo);
    byte[] archivo = null;
    String tipoContenido = null;//from   w ww  .  j  av a  2 s  .co  m
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(jefeSeccions);
        tipoContenido = "application/pdf";
        break;
    case "CSV":
        archivo = generaCsv(jefeSeccions);
        tipoContenido = "text/csv";
        break;
    case "XLS":
        archivo = generaXls(jefeSeccions);
        tipoContenido = "application/vnd.ms-excel";
    }

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("jefeSeccion.lista.label", null, request.getLocale());
    helper.setSubject(messageSource.getMessage("envia.correo.titulo.message", new String[] { titulo },
            request.getLocale()));
    helper.setText(messageSource.getMessage("envia.correo.contenido.message", new String[] { titulo },
            request.getLocale()), true);
    helper.addAttachment(titulo + "." + tipo, new ByteArrayDataSource(archivo, tipoContenido));
    mailSender.send(message);
}

From source file:com.cfitzarl.cfjwed.service.impl.EmailDispatchingServiceImpl.java

/** {@inheritDoc} **/
@Override//from   w w w .  j  a  v  a 2s  .  co  m
public void send(String to, String subject, String template, Map<String, Object> attrs) {
    // Add message source decorator to attributes list for localization
    attrs.put("localeSource", localizationService);

    String htmlFilename = String.format("/email-templates/%s-html.vm", template);
    String textFilename = String.format("/email-templates/%s-text.vm", template);

    String htmlContent = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, htmlFilename, "UTF-8",
            attrs);
    String textContent = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, textFilename, "UTF-8",
            attrs);

    try {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        String fromEmail = configDao.findByKey(ConfigKey.EMAIL).getValue();
        String fromTitle = configDao.findByKey(ConfigKey.TITLE).getValue();

        String from = String.format("%s <%s>", fromTitle, fromEmail);

        helper.setTo(to);
        helper.setSubject(subject);
        helper.setFrom(from);
        helper.setReplyTo(from);
        helper.setText(textContent, htmlContent);

        taskExecutor.submit(new MailRunner(message, javaMailSender));
    } catch (MessagingException e) {
        LOGGER.error("Error generating mail message", e);
    }
}

From source file:hornet.framework.mail.MailServiceImpl.java

/**
 * Ajouter destinataires./*from w w  w .  j  a  va2s.c  o m*/
 *
 * @param helper
 *            Composant de prparation de message
 * @param destinataires
 *            Les destinataires
 * @throws MessagingException
 *             En cas d'invalidit d'adresse de courriel
 */
protected void ajouterDestinataires(final MimeMessageHelper helper, final String... destinataires)
        throws MessagingException {

    helper.setTo(destinataires);
}

From source file:mx.edu.um.mateo.rh.web.CategoriaController.java

private void enviaCorreo(String tipo, List<Categoria> categorias, HttpServletRequest request)
        throws JRException, MessagingException {
    log.debug("Enviando correo {}", tipo);
    byte[] archivo = null;
    String tipoContenido = null;// w ww. j  a  v a  2s .c o m
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(categorias);
        tipoContenido = "application/pdf";
        break;
    case "CSV":
        archivo = generaCsv(categorias);
        tipoContenido = "text/csv";
        break;
    case "XLS":
        archivo = generaXls(categorias);
        tipoContenido = "application/vnd.ms-excel";
    }

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("categoria.lista.label", null, request.getLocale());
    helper.setSubject(messageSource.getMessage("envia.correo.titulo.message", new String[] { titulo },
            request.getLocale()));
    helper.setText(messageSource.getMessage("envia.correo.contenido.message", new String[] { titulo },
            request.getLocale()), true);
    helper.addAttachment(titulo + "." + tipo, new ByteArrayDataSource(archivo, tipoContenido));
    mailSender.send(message);
}

From source file:com.jaspersoft.jasperserver.war.mail.impl.MailServiceImpl.java

public void sendEmailNotification(String subject, String body, String mailTo) {
    try {// www.  j a  va 2  s .c om
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true,
                encodingProvider.getCharacterEncoding());
        messageHelper.setFrom(mailFromAddress);
        messageHelper.setSubject(subject);

        StringBuffer messageText = new StringBuffer();

        messageText.append(body);

        messageHelper.setTo(mailTo);
        messageHelper.setText(messageText.toString());
        javaMailSender.send(message);
    } catch (MessagingException e) {
        log.error("Error while sending mail", e);
        throw new JSExceptionWrapper(e);
    }
}

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

/**
 * Finish launch notification//w w w .  j  av  a 2s  . co m
 *
 * @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:eu.openanalytics.rsb.component.EmailDepositHandler.java

public void handleResult(final MultiFilesResult result) throws MessagingException, IOException {
    final Serializable responseBody = result.getMeta().get(EMAIL_BODY_META_NAME);
    final String responseText = responseBody instanceof File ? FileUtils.readFileToString((File) responseBody)
            : responseBody.toString();//from  w  ww  .ja v  a2 s  . com

    final MimeMessage mimeMessage = mailSender.createMimeMessage();
    final MimeMessageHelper mmh = new MimeMessageHelper(mimeMessage, true);

    mmh.setFrom((String) result.getMeta().get(EMAIL_ADDRESSEE_META_NAME));
    mmh.setTo((String) result.getMeta().get(EMAIL_REPLY_TO_META_NAME));
    mmh.setCc((String[]) result.getMeta().get(EMAIL_REPLY_CC_META_NAME));
    mmh.setSubject("RE: " + result.getMeta().get(EMAIL_SUBJECT_META_NAME));

    if (result.isSuccess()) {
        mmh.setText(responseText);
        for (final File resultFile : result.getPayload()) {
            mmh.addAttachment(resultFile.getName(), resultFile);
        }
    } else {
        mmh.setText(FileUtils.readFileToString(result.getPayload()[0]));
    }

    final Message<MimeMailMessage> message = new GenericMessage<MimeMailMessage>(new MimeMailMessage(mmh));
    outboundEmailChannel.send(message);
}

From source file:mx.edu.um.mateo.rh.web.ClaveEmpleadoController.java

private void enviaCorreo(String tipo, List<ClaveEmpleado> claveEmpleados, HttpServletRequest request)
        throws JRException, MessagingException {
    log.debug("Enviando correo {}", tipo);
    byte[] archivo = null;
    String tipoContenido = null;/*from  w  w w  .  j ava2s  .com*/
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(claveEmpleados);
        tipoContenido = "application/pdf";
        break;
    case "CSV":
        archivo = generaCsv(claveEmpleados);
        tipoContenido = "text/csv";
        break;
    case "XLS":
        archivo = generaXls(claveEmpleados);
        tipoContenido = "application/vnd.ms-excel";
    }

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("claveEmpleado.lista.label", null, request.getLocale());
    helper.setSubject(messageSource.getMessage("envia.correo.titulo.message", new String[] { titulo },
            request.getLocale()));
    helper.setText(messageSource.getMessage("envia.correo.contenido.message", new String[] { titulo },
            request.getLocale()), true);
    helper.addAttachment(titulo + "." + tipo, new ByteArrayDataSource(archivo, tipoContenido));
    mailSender.send(message);
}