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

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

Introduction

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

Prototype

public void setText(String plainText, String htmlText) throws MessagingException 

Source Link

Document

Set the given plain text and HTML text as alternatives, offering both options to the email client.

Usage

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  w w  w  .  j  av a 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:com.exp.tracker.utils.EmailUtility.java

/**
 * Sends an email.//from  w ww .ja  v  a  2s  .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.epam.ta.reportportal.util.email.EmailService.java

/**
 * Restore password email//from www .  j  a  v  a 2  s  .c  o 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:com.hmsinc.epicenter.surveillance.notification.EmailMessageRenderer.java

public void prepare(final MimeMessageHelper message, String encoding, final Event event,
        final EpiCenterUser user) throws MessagingException, VelocityException {

    message.setSubject(EventNotifierUtils.getTemplate(event, user, "/templates/email-subject.vm", encoding, url,
            velocityEngine));/*from w w w .j  av  a 2  s . co m*/

    String textContent = EventNotifierUtils.getTemplate(event, user, "/templates/email-text.vm", encoding, url,
            velocityEngine);
    String htmlContent = EventNotifierUtils.getTemplate(event, user, "/templates/email-html.vm", encoding, url,
            velocityEngine);

    message.setText(wrap(textContent), htmlContent);
}

From source file:jedai.business.JRegistrationService.java

/**
 * @param user//  w w w .  j a  va 2 s . c  om
 */
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:eu.trentorise.smartcampus.citizenportal.service.EmailService.java

public String sendSimpleMail(final String recipientName, final String recipientEmail, final String subject,
        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"));
    ctx.setVariable("text", subject);

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
    message.setSubject("Graduatoria Edilizia Abitativa");
    //message.setFrom("thymeleaf@example.com");
    message.setFrom("myweb.edilizia@comunitadellavallagarina.tn.it");
    message.setTo(recipientEmail);/*from w  ww  . ja va2s  .  c om*/

    // Create the HTML body using Thymeleaf
    final String htmlContent = this.templateEngine.process("email-simple.html", ctx);
    message.setText(htmlContent, true /* isHtml */);

    // Send email
    this.mailSender.send(mimeMessage);

    return recipientName;
}

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

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

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    String titulo = messageSource.getMessage("dependiente.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:jedai.business.JRegistrationService.java

/**
 * @param user//w w  w.  j a v  a2 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);
}

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

/**
 * {@inheritDoc}//from ww  w  . j  a  v  a2  s  . c o m
 */
@Override
public void envoyer(final String expediteur, final String sujet, final String message,
        final Map<String, Object> paramMap, final String... destinataires) {

    try {
        final Session session = ((JavaMailSenderImpl) mailSender).getSession();
        HornetMimeMessage mMessage = null;
        if (messageIdDomainName == null || messageIdDomainName.length() == 0) {
            mMessage = new HornetMimeMessage(nomApplication, session);
        } else {
            mMessage = new HornetMimeMessage(nomApplication, messageIdDomainName, session);
        }

        mMessage.setHeader("Content-Type", "text/html");
        final MimeMessageHelper helper = new MimeMessageHelper(mMessage, true, CharEncoding.UTF_8);

        addExtraSmtpField(paramMap, helper);

        helper.setFrom(expediteur);

        ajouterDestinataires(helper, destinataires);

        helper.setSubject(sujet);
        // message aux formats texte et html
        helper.setText(preparerMessageTexte(message), preparerMessageHTML(message));

        mailSender.send(mMessage);
    } catch (final MailSendException mse) {
        throw toBusinessException(mse);
    } catch (final Exception e) {
        throw new BusinessException("erreur.envoi.courriel", e);
    }
}