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:br.com.jreader.model.services.EmailService.java

public void sendEmailRegistration(final User user) throws MailException {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @Override/*from ww  w .  ja  v  a2 s  .c  o m*/
        public void prepare(MimeMessage mm) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mm);
            message.setTo(user.getEmail());
            message.setSubject(
                    JReaderUtils.getTranslation("br.com.jreader.util.lang.messages", "subject_mail_confirm"));
            message.setFrom(JReaderUtils.getTranslation("br.com.jreader.util.lang.messages", "app_title"));
            Map<String, Object> model = new HashMap<>();
            model.put("user", user);
            model.put("context", Context.getContextPath());
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "email-templates/registration-confirmation.vm", "UTF-8", model);
            message.setText(text, true);

        }
    };
    this.mailSender.send(preparator);
}

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

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

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("estudiosEmpleado.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.enonic.cms.core.mail.AbstractSendMailService.java

public final void sendMail(AbstractMailTemplate template) {
    try {/*from   w  w w.  j av  a 2  s.c om*/
        MessageSettings settings = new MessageSettings();

        setFromSettings(template, settings);

        settings.setBody(template.getBody());

        final MimeMessageHelper message = createMessage(settings,
                template.isHtml() || !template.getAttachments().isEmpty());
        message.setSubject(template.getSubject());

        final Map<String, InputStream> attachments = template.getAttachments();

        for (final Map.Entry<String, InputStream> attachment : attachments.entrySet()) {
            message.addAttachment(attachment.getKey(),
                    new ByteArrayResource(IOUtils.toByteArray(attachment.getValue())));
        }

        if (template.isHtml()) {
            message.setText("[You need html supported mail client to read this email]", template.getBody());
        } else {
            message.setText(template.getBody());
        }

        if (template.getMailRecipients().size() == 0) {
            this.log.info("No recipients specified, mail not sent.");
        }

        for (MailRecipient recipient : template.getMailRecipients()) {
            if (recipient.getEmail() != null) {
                final MailRecipientType type = recipient.getType();

                switch (type) {
                case TO_RECIPIENT:
                    message.addTo(recipient.getEmail(), recipient.getName());
                    break;
                case BCC_RECIPIENT:
                    message.addBcc(recipient.getEmail(), recipient.getName());
                    break;
                case CC_RECIPIENT:
                    message.addCc(recipient.getEmail(), recipient.getName());
                    break;
                default:
                    throw new RuntimeException("Unknown recipient type: " + type);
                }
            }
        }

        sendMessage(message);
    } catch (Exception e) {
        this.log.error("Failed to send mail", e);
    }
}

From source file:org.fuin.auction.command.server.base.MailManager.java

/**
 * Creates a welcome mail with a unique identifier to verify the email
 * address.//  w  w  w .  j  a  v a  2  s .co m
 * 
 * @param event
 *            Event to handle.
 */
@EventHandler
public final void handle(final UserCreatedEvent event) {

    if (LOG.isDebugEnabled()) {
        LOG.debug("SEND user created mail to " + event.getEmail() + " [securityToken='"
                + event.getSecurityToken() + "']");
    }

    final MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(final MimeMessage mimeMessage) throws Exception {
            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(event.getEmail().toString());
            message.setFrom(mailProperties.getProperty("sender"));
            final Map<String, String> varMap = new HashMap<String, String>();
            varMap.put("email", event.getEmail().toString());
            varMap.put("userName", event.getUserName().toString());
            varMap.put("securityToken", event.getSecurityToken().toString());
            final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "user-created-mail.vm", varMap);
            message.setText(text, true);
        }
    };
    this.mailSender.send(preparator);

}

From source file:io.gravitee.management.service.impl.EmailServiceImpl.java

private String addResourcesInMessage(final MimeMessageHelper mailMessage, final String htmlText)
        throws Exception {
    final Document document = Jsoup.parse(htmlText);

    final List<String> resources = new ArrayList<>();

    final Elements imageElements = document.getElementsByTag("img");
    resources.addAll(/*from   ww w. j av a2 s. c  o m*/
            imageElements.stream().filter(imageElement -> imageElement.hasAttr("src")).map(imageElement -> {
                final String src = imageElement.attr("src");
                imageElement.attr("src", "cid:" + src);
                return src;
            }).collect(Collectors.toList()));

    final String html = document.html();
    mailMessage.setText(html, true);

    for (final String res : resources) {
        final FileSystemResource templateResource = new FileSystemResource(new File(templatesPath, res));
        mailMessage.addInline(res, templateResource,
                MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(res));
    }

    return html;
}

From source file:cdr.forms.EmailNotificationHandler.java

@Override
public void notifyError(Deposit deposit, DepositResult result) {

    Form form = deposit.getForm();/*  w w  w.  j  a v  a2  s  . com*/
    String formId = deposit.getFormId();
    String depositorEmail = deposit.getReceiptEmailAddress();
    List<String> recipients = deposit.getAllDepositNoticeToEmailAddresses();

    // put data into the model
    HashMap<String, Object> model = new HashMap<String, Object>();
    model.put("deposit", deposit);
    model.put("form", form);
    model.put("formId", formId);
    model.put("result", result);
    model.put("depositorEmail", depositorEmail);
    model.put("siteUrl", this.getSiteUrl());
    model.put("siteName", this.getSiteName());
    model.put("receivedDate", new Date(System.currentTimeMillis()));
    StringWriter htmlsw = new StringWriter();
    StringWriter textsw = new StringWriter();

    try {
        depositErrorHtmlTemplate.process(model, htmlsw);
        depositErrorTextTemplate.process(model, textsw);
    } catch (TemplateException e) {
        LOG.error("cannot process email template", e);
        return;
    } catch (IOException e) {
        LOG.error("cannot process email template", e);
        return;
    }

    try {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED);

        if (administratorAddress != null && administratorAddress.trim().length() > 0) {
            message.addTo(this.administratorAddress);
        }

        for (String recipient : recipients) {
            message.addTo(recipient);
        }

        message.setSubject("Deposit Error for " + form.getTitle());
        message.setFrom(this.getFromAddress());
        message.setText(textsw.toString(), htmlsw.toString());
        this.mailSender.send(mimeMessage);
    } catch (MessagingException e) {
        LOG.error("problem sending error notification message", e);
        return;
    }

}

From source file:com.sisrni.service.FreeMarkerMailServiceImpl.java

private MimeMessagePreparator getMessagePreparator(final Object obj) throws Exception {

    try {//from w  ww  .  j a v  a 2s. c  o m

        MimeMessagePreparator preparator = new MimeMessagePreparator() {

            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

                helper.setSubject(getSubJect());
                //helper.setFrom("tgraduacion01@gmail.com" );
                helper.setTo(getSetToMail());
                helper.setSentDate(new Date());

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

                String text = geFreeMarkerTemplateContent(model);
                System.out.println("Contenido de plantilla : " + text);

                // use the true flag to indicate you need a multipart message
                helper.setText(text, true);

                //Additionally, let's add a resource as an attachment as well.
                //helper.addAttachment("cutie.png", new ClassPathResource("linux-icon.png"));
            }
        };
        return preparator;
    } catch (Exception ex) {
        throw new Exception(
                "Error class  FreeMarkerMailServiceImpl - getMessagePreparator()\n" + ex.getMessage(),
                ex.getCause());
    }

}

From source file:com.hmsinc.epicenter.webapp.PasswordResetController.java

/**
 * @param token/*w w w .  j  ava2  s  . c om*/
 * @param url
 */
private void sendPasswordResetEmail(final PasswordResetToken token, final String url) {

    final MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {

            final EpiCenterUser user = token.getUser();

            String encoding = "UTF-8";
            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage,
                    MimeMessageHelper.MULTIPART_MODE_RELATED, encoding);
            message.setTo(user.getEmailAddress());
            message.setFrom(applicationProperties.getProperty("epicenter.mail.from"));
            message.setSubject(mailSubject);

            final Map<String, Object> model = new HashMap<String, Object>();
            model.put("url", url);
            model.put("username", user.getUsername());
            model.put("token", token.getToken());

            message.setText(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, TEMPLATE_TEXT, model),
                    VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, TEMPLATE_HTML, model));
        }
    };

    mailSender.send(preparator);
}

From source file:it.jugpadova.blo.ParticipantBo.java

/**
 * General participant mail sender//  w ww  .  ja va2s  .c  o m
 *
 * @param participant
 * @param baseUrl
 * @param subject
 * @param oneWayCode
 * @param template
 */
private void sendEmail(final Participant participant, final String baseUrl, final String subject,
        final String template, final Resource attachment, final String attachmentName) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @SuppressWarnings(value = "unchecked")
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
            message.setTo(participant.getEmail());
            message.setFrom(conf.getConfirmationSenderEmailAddress());
            message.setSubject(subject);
            Map model = new HashMap();
            model.put("participant", participant);
            model.put("baseUrl", baseUrl);
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model);
            message.setText(text, true);
            if (attachment != null) {
                message.addAttachment(attachmentName, attachment);
            }
        }
    };
    this.mailSender.send(preparator);
}