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.hmsinc.epicenter.webapp.PasswordResetController.java

/**
 * @param token// w  ww  .  jav  a  2s.  c o  m
 * @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:com.epam.ta.reportportal.util.email.EmailService.java

public void sendConfirmationEmail(CreateUserRQFull req, String basicUrl) {
    MimeMessagePreparator preparator = mimeMessage -> {
        URL logoImg = this.getClass().getClassLoader().getResource(LOGO);
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "utf-8");
        message.setSubject("Welcome to Report Portal");
        message.setTo(req.getEmail());
        setFrom(message);//w w  w .j  a va  2s  .c o  m

        Map<String, Object> email = new HashMap<>();
        email.put("url", basicUrl);
        email.put("login", normalizeUsername(req.getLogin()));
        email.put("password", req.getPassword());
        String text = templateEngine.merge("create-user-template.vm", email);
        message.setText(text, true);
        message.addInline("logoimg", new UrlResource(logoImg));
    };
    this.send(preparator);
}

From source file:org.runway.users.service.UserPasswordResetServiceImpl.java

private void createAndSendEmail(User user, UserPasswordReset resetRequest) {

    //SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
    MimeMessageHelper msg = new MimeMailMessage(mailSender.createMimeMailMessage()).getMimeMessageHelper();

    String title = "Peoplebees password reset request ";

    try {//from  ww w  . ja v a 2 s.com
        msg.setFrom("admin@peoplebees.com");
        msg.setTo(user.getEmail());
        msg.setSubject(title);

        String resetLink = UserLinkHelper.createPasswordResetLink(resetRequest);
        String message = createMessage(title, resetRequest.getHostName(), resetLink, user);
        msg.setText(message, true);

        this.mailSender.sendMail(msg);

    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

From source file:fr.mycellar.application.contact.impl.ContactServiceImpl.java

@Override
@Scheduled(cron = "0 0 0 * * *")
public void sendReminders() {
    final String[] to = configurationService.getReminderAddressReceivers();
    if (to.length == 0) {
        return;//from  w ww  . j a  v  a  2  s .c  om
    }
    final StringBuilder content = new StringBuilder();
    List<Contact> contacts = contactRepository.getAllToContact();
    if ((contacts != null) && (contacts.size() > 0)) {
        for (Contact contact : contacts) {
            content.append("Domaine ").append(contact.getProducer().getName()).append("  recontacter le ")
                    .append(contact.getNext().toString("dd/MM/yyyy")).append("\r\n");
            content.append("Dernier contact le ").append(contact.getCurrent().toString("dd/MM/yyyy"))
                    .append(" :").append("\r\n").append(contact.getText()).append("\r\n");
            content.append("------------------------------------------------").append("\r\n");
        }
        final String from = configurationService.getMailAddressSender();
        MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
                helper.setFrom(from);
                helper.setSubject("Contacts  recontacter");
                helper.setText(content.toString());
                helper.setTo(to);
            }
        };
        try {
            javaMailSender.send(mimeMessagePreparator);
        } catch (Exception e) {
            throw new RuntimeException("Cannot send email.", e);
        }
    }
}

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

/**
 * General participant mail sender/*from   w  ww  .j a  v a 2  s  .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);
}

From source file:de.metas.procurement.webui.service.impl.LoginService.java

@Override
public void sendPasswordResetKey(final String email, final URI passwordResetURI) {
    Preconditions.checkNotNull(passwordResetURI, "passwordResetURI is null");

    MimeMessage mail = emailSender.createMimeMessage();
    try {//ww  w .  j  a va  2s  . c  om
        MimeMessageHelper helper = new MimeMessageHelper(mail, true); // multipart=true

        if (emailFrom != null && !emailFrom.trim().isEmpty()) {
            helper.setFrom(emailFrom.trim());
        }
        helper.setTo(email);
        helper.setSubject(i18n.get("PasswordReset.email.subject"));
        helper.setText(i18n.get("PasswordReset.email.content", passwordResetURI));
    } catch (MessagingException e) {
        e.printStackTrace();
    } finally {
    }
    emailSender.send(mail);
}

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

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

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("diaFeriado.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:thymeleafexamples.springmail.service.EmailService.java

public void sendEditableMail(final String recipientName, final String recipientEmail, final String htmlContent,
        final Locale locale) throws MessagingException {

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8");
    message.setSubject("Example editable HTML email");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);

    // FIXME: duplicated images in src/main/resources and src/main/webapp
    // 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"));

    final StaticTemplateExecutor templateExecutor = new StaticTemplateExecutor(ctx, messageResolver,
            HTML5.getTemplateModeName());
    final String output = templateExecutor.processTemplateCode(htmlContent);
    message.setText(output, true /* isHtml */);

    // Add the inline images, referenced from the HTML code as "cid:image-name"
    message.addInline("background", new ClassPathResource(BACKGROUND_IMAGE), PNG_MIME);
    message.addInline("logo-background", new ClassPathResource(LOGO_BACKGROUND_IMAGE), PNG_MIME);
    message.addInline("thymeleaf-banner", new ClassPathResource(THYMELEAF_BANNER_IMAGE), PNG_MIME);
    message.addInline("thymeleaf-logo", new ClassPathResource(THYMELEAF_LOGO_IMAGE), PNG_MIME);

    // Send mail//from   www .  ja  va  2 s. c o m
    this.mailSender.send(mimeMessage);

}

From source file:gr.abiss.calipso.service.EmailService.java

@Async
public void sendEmail(final String subject, final String templateName, String emailTo, String emailFrom,
        final Context ctx) {
    try {//from ww w.j a  v  a 2s.  co  m
        // Prepare message using a Spring helper
        final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
        message.setSubject(subject);
        message.setFrom(emailFrom);
        message.setTo(emailTo);
        ctx.setVariable("baseUrl", this.baseUrl);
        // Create the HTML body using Thymeleaf
        final String htmlContent = this.templateEngine.process(templateName, ctx);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending email body: " + htmlContent);
        }
        message.setText(htmlContent, true /* isHtml */);

        // Send email
        if (StringUtils.isNotBlank(ConfigurationFactory.getConfiguration().getString("mail.server.host"))) {
            this.mailSender.send(mimeMessage);
        } else {
            LOGGER.warn("Skipped sending email as mail.server.host property is empty");
        }
    } catch (Exception e) {
        LOGGER.error("Failed to send email: ", e);
    }

}

From source file:thymeleafexamples.springmail.service.EmailService.java

public void sendMailWithAttachment(final String recipientName, final String recipientEmail,
        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("subscriptionDate", new Date());
    ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8");
    message.setSubject("Example HTML email with attachment");
    message.setFrom("thymeleaf@example.com");
    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/*ww  w.j a v  a2s .  co  m*/
    this.mailSender.send(mimeMessage);

}