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:mx.edu.um.mateo.general.web.BaseController.java

protected void enviaCorreo(String tipo, List<?> lista, HttpServletRequest request, String nombre,
        String tipoReporte, Long id) throws ReporteException {
    try {/*from   w w  w. j  ava 2 s .  c  om*/
        log.debug("Enviando correo {}", tipo);
        byte[] archivo = null;
        String tipoContenido = null;
        switch (tipo) {
        case "PDF":
            archivo = generaPdf(lista, nombre, tipoReporte, id);
            tipoContenido = "application/pdf";
            break;
        case "CSV":
            archivo = generaCsv(lista, nombre, tipoReporte, id);
            tipoContenido = "text/csv";
            break;
        case "XLS":
            archivo = generaXls(lista, nombre, tipoReporte, id);
            tipoContenido = "application/vnd.ms-excel";
        }

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(ambiente.obtieneUsuario().getCorreo());
        String titulo = messageSource.getMessage(nombre + ".reporte.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);
    } catch (JRException | MessagingException e) {
        throw new ReporteException("No se pudo generar el reporte", e);
    }
}

From source file:br.com.semanticwot.cd.infra.MailManager.java

public void sendNewPurchaseMail(SystemUser user, String emailTemplate) throws MessagingException {

    Object[] args = { user.getName(), user.getUsername() };
    MessageFormat fmt = new MessageFormat(emailTemplate);

    MimeMessage message = mailer.createMimeMessage();

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

    // use the true flag to indicate the text included is HTML
    helper.setText(fmt.format(args), true);

    System.out.println("Passei por aqui " + user.getUsername());

    //SimpleMailMessage email = new SimpleMailMessage();
    helper.setFrom(user.getUsername());//w w w.  ja v a  2  s.c o  m

    // Somente por enquanto, que esta em teste. 
    // Em producao mudar para helper.setTo(user.getLogin());
    helper.setTo("notlian.junior@gmail.com");

    helper.setSubject("PSWoT Register");
    mailer.send(message);
}

From source file:com.exp.tracker.utils.EmailUtility.java

/**
 * Sends an email.//from   w w w  .  j  a  v a 2 s  .co m
 * 
 * @param emailIdStrings
 *            A String array containing a list of email addresses.
 * @param emailSubject
 *            The subject of the email.
 * @param messageContent
 *            The message body.
 * @param emailAttachments
 *            A map containing any attachments. The key should be the file
 *            name. The value os a byte[] containing the binary
 *            representation of the attachment.
 * @throws EmailCommunicationException
 *             If any exception occurs.
 */
public void sendEmail(String[] emailIdStrings, String emailSubject, String messageContent,
        Map<String, byte[]> emailAttachments) throws EmailCommunicationException {
    if (null == emailIdStrings) {
        throw new EmailCommunicationException("Null array passed to this method.");
    }
    if (emailIdStrings.length == 0) {
        throw new EmailCommunicationException("No email addresses were provided. Array was empty.");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("About to send an email.");
    }

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

        helper.setFrom(fromAccount, fromName);
        InternetAddress[] toListArray = new InternetAddress[emailIdStrings.length];
        for (int i = 0; i < emailIdStrings.length; i++) {
            toListArray[i] = new InternetAddress(emailIdStrings[i]);
        }
        //To
        helper.setTo(toListArray);
        //Subject
        helper.setSubject(emailSubject);
        //Body
        helper.setText(messageContent, true);
        //Attachments
        if (null != emailAttachments) {
            Set<String> attachmentFileNames = emailAttachments.keySet();
            for (String fileName : attachmentFileNames) {
                helper.addAttachment(fileName,
                        new ByteArrayDataSource(emailAttachments.get(fileName), "application/octet-stream"));
            }
        }

        javaMailSender.send(mimeMessage);
        System.out.println("Mail sent successfully.");
    } catch (MessagingException e) {
        throw new EmailCommunicationException("Error sending email.", e);
    } catch (UnsupportedEncodingException e) {
        throw new EmailCommunicationException("Error sending email. Unsupported encoding.", e);
    }
}

From source file:com.springstudy.utils.email.MimeMailService.java

/**
 * ??MIME?.//from  w  w  w.  java  2  s .c  o m
 */
public boolean sendNotificationMail(com.gmk.framework.common.utils.email.Email email) {
    try {
        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, DEFAULT_ENCODING);
        //??????
        String from = Global.getConfig("productName");
        if (StringUtils.isNotEmpty(email.getFrom())) {
            from = from + "-" + email.getFrom();
        }
        helper.setFrom(Global.getConfig("mailFrom"), from);
        helper.setTo(email.getAddress());
        if (StringUtils.isNotEmpty(email.getCc())) {
            String cc[] = email.getCc().split(";");
            helper.setCc(cc);//?
        }
        //
        helper.setSubject(email.getSubject());
        //
        if (StringUtils.isNotEmpty(email.getTemplate())) {
            String content = generateContent(email.getTemplate(), email.getContentMap());
            helper.setText(content, true);
        } else {
            helper.setText(email.getContent());
        }
        //
        if (ListUtils.isNotEmpty(email.getAttachment())) {
            for (File file : email.getAttachment()) {
                helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
            }
        }
        mailSender.send(msg);
        logger.info("HTML??");
        return true;
    } catch (MessagingException e) {
        logger.error(email.getAddressee() + "-" + email.getSubject() + "-" + "", e);
    } catch (Exception e) {
        logger.error(email.getAddressee() + "-" + email.getSubject() + "-" + "??", e);
    }
    return false;
}

From source file:cz.zcu.kiv.eegdatabase.data.service.SpringJavaMailService.java

@Override
public void sendNotification(String email, ArticleComment comment, Locale locale) throws MailException {

    try {//ww  w.  j  av a  2s  .  c o m
        String articleURL = "http://" + domain + "/articles/detail.html?articleId="
                + comment.getArticle().getArticleId();
        //System.out.println(articleURL);
        String subject = messageSource.getMessage("articles.comments.email.subscribtion.subject",
                new String[] { comment.getArticle().getTitle(), comment.getPerson().getUsername() }, locale);
        //System.out.println(subject);
        String emailBody = "<html><body>";

        emailBody += "<p>" + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part1",
                new String[] { comment.getArticle().getTitle() }, locale) + "";
        emailBody += "&nbsp;(<a href=\"" + articleURL + "\" target=\"_blank\">" + articleURL
                + "</a>)</p><br />";
        emailBody += "<h3>Text:</h3> <p>" + comment.getText() + "</p><br />";
        emailBody += "<p>"
                + messageSource.getMessage("articles.group.email.subscribtion.body.text.part2", null, locale)
                + "</p>";
        emailBody += "</body></html>";

        //System.out.println(emailBody);
        log.debug("email body: " + emailBody);

        log.debug("Composing e-mail message");
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
        message.setFrom(mailMessage.getFrom());

        //  message.setContent("text/html");
        message.setTo(email);
        //helper.setFrom(messageSource.getMessage("registration.email.from", null, RequestContextUtils.getLocale(request)));
        message.setSubject(subject);
        message.setText(emailBody, true);

        log.debug("Sending e-mail" + message);
        log.debug("mailSender" + mailSender);
        mailSender.send(mimeMessage);
        log.debug("E-mail was sent");
    } catch (MailException e) {
        log.error("E-mail for subscribers was NOT sent");
        log.error(e.getMessage(), e);
    } catch (MessagingException e) {
        log.error("E-mail for subscribers was NOT sent");
        log.error(e.getMessage(), e);
    }
}

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);

    // 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// w  w  w.  ja  v  a  2  s  .co  m
    this.mailSender.send(mimeMessage);

    return recipientName + "OK";
}

From source file:cz.zcu.kiv.eegdatabase.data.service.SpringJavaMailService.java

@Override
public void sendNotification(String email, Article article, Locale locale) {

    try {/*from   w w  w . j a  va2s .  c o m*/
        String articleURL = "http://" + domain + "/articles/detail.html?articleId=" + article.getArticleId();
        // System.out.println(articleURL);
        String subject = messageSource.getMessage("articles.group.email.subscribtion.subject",
                new String[] { article.getTitle(), article.getPerson().getUsername() }, locale);
        // System.out.println(subject);
        String emailBody = "<html><body>";

        emailBody += "<p>" + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part1",
                new String[] { article.getTitle(),
                        article.getResearchGroup() != null ? article.getResearchGroup().getTitle()
                                : "Public articles" },
                locale) + "";
        emailBody += "&nbsp;(<a href=\"" + articleURL + "\" target=\"_blank\">" + articleURL
                + "</a>)</p><br />";
        emailBody += "<h3>" + article.getTitle() + "</h3> <p>" + article.getText() + "</p><br />";
        emailBody += "<p>"
                + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part2", null, locale)
                + "</p>";
        emailBody += "</body></html>";

        // System.out.println(emailBody);
        log.debug("email body: " + emailBody);

        log.debug("Composing e-mail message");
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
        message.setFrom(mailMessage.getFrom());

        // message.setContent("text/html");
        message.setTo(email);
        // helper.setFrom(messageSource.getMessage("registration.email.from", null, RequestContextUtils.getLocale(request)));
        message.setSubject(subject);
        message.setText(emailBody, true);

        log.debug("Sending e-mail" + message);
        log.debug("mailSender" + mailSender);
        mailSender.send(mimeMessage);
        log.debug("E-mail was sent");

    } catch (MailException e) {
        log.error("E-mail for subscribers was NOT sent");
        log.error(e.getMessage(), e);
    } catch (MessagingException e) {
        log.error("E-mail for subscribers was NOT sent");
        log.error(e.getMessage(), e);
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.article.AddArticleCommentController.java

private void sendNotification(String email, ArticleComment comment, HttpServletRequest request)
        throws MessagingException {
    String articleURL = "http://" + domain + "/articles/detail.html?articleId="
            + comment.getArticle().getArticleId();
    //System.out.println(articleURL);
    String subject = messageSource.getMessage("articles.group.email.subscribtion.subject",
            new String[] { comment.getArticle().getTitle(), comment.getPerson().getUsername() },
            RequestContextUtils.getLocale(request));
    //System.out.println(subject);
    String emailBody = "<html><body>";

    emailBody += "<p>"
            + messageSource.getMessage("articles.group.email.subscribtion.body.text.part1",
                    new String[] { comment.getArticle().getTitle() }, RequestContextUtils.getLocale(request))
            + "";
    emailBody += "&nbsp;(<a href=\"" + articleURL + "\" target=\"_blank\">" + articleURL + "</a>)</p><br />";
    emailBody += "<h3>Text:</h3> <p>" + comment.getText() + "</p><br />";
    emailBody += "<p>" + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part2", null,
            RequestContextUtils.getLocale(request)) + "</p>";
    emailBody += "</body></html>";

    //System.out.println(emailBody);
    log.debug("email body: " + emailBody);

    log.debug("Composing e-mail message");
    MimeMessage mimeMessage = mailSender.createMimeMessage();

    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
    message.setFrom(mailMessage.getFrom());

    //  message.setContent("text/html");
    message.setTo(email);
    //helper.setFrom(messageSource.getMessage("registration.email.from", null, RequestContextUtils.getLocale(request)));
    message.setSubject(subject);//ww  w  . j  a  v a 2s  .c o m
    message.setText(emailBody, true);

    try {
        log.debug("Sending e-mail" + message);
        log.debug("mailSender" + mailSender);
        log.debug("smtp " + mailSender.getHost());
        mailSender.send(mimeMessage);
        log.debug("E-mail was sent");
    } catch (MailException e) {
        log.error("E-mail was NOT sent");
        log.error(e);
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.article.AddArticleController.java

private void sendNotification(String email, Article article, HttpServletRequest request)
        throws MessagingException {
    String articleURL = "http://" + domain + "/articles/detail.html?articleId=" + article.getArticleId();
    //System.out.println(articleURL);
    String subject = messageSource.getMessage("articles.group.email.subscribtion.subject",
            new String[] { article.getTitle(), article.getPerson().getUsername() },
            RequestContextUtils.getLocale(request));
    //System.out.println(subject);
    String emailBody = "<html><body>";

    emailBody += "<p>" + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part1",
            new String[] { article.getTitle() }, RequestContextUtils.getLocale(request)) + "";
    emailBody += "&nbsp;(<a href=\"" + articleURL + "\" target=\"_blank\">" + articleURL + "</a>)</p><br />";
    emailBody += "<h3>" + article.getTitle() + "</h3> <p>" + article.getText() + "</p><br />";
    emailBody += "<p>" + messageSource.getMessage("articles.comments.email.subscribtion.body.text.part2", null,
            RequestContextUtils.getLocale(request)) + "</p>";
    emailBody += "</body></html>";

    //System.out.println(emailBody);
    log.debug("email body: " + emailBody);

    log.debug("Composing e-mail message");
    MimeMessage mimeMessage = mailSender.createMimeMessage();

    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
    message.setFrom(mailMessage.getFrom());

    //  message.setContent("text/html");
    message.setTo(email);
    //helper.setFrom(messageSource.getMessage("registration.email.from", null, RequestContextUtils.getLocale(request)));
    message.setSubject(subject);/*from w  w  w. ja v  a  2  s  .c om*/
    message.setText(emailBody, true);

    try {
        log.debug("Sending e-mail" + message);
        log.debug("mailSender" + mailSender);
        log.debug("smtp " + mailSender.getHost());
        mailSender.send(mimeMessage);
        log.debug("E-mail was sent");
    } catch (MailException e) {
        log.error("E-mail was NOT sent");
        log.error(e);
    }
}