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

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

Introduction

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

Prototype

public void setSubject(String subject) throws MessagingException 

Source Link

Document

Set the subject of the message, using the correct encoding.

Usage

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;/*from   w w  w .  j  a  v a  2s. c  om*/
    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:mx.edu.um.mateo.rh.web.JefeRHController.java

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

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

/**
 * {@inheritDoc}/* w ww  .  j a  v  a2s. c  o m*/
 */
@Override
public void notifySiteCodeReservation(String userName, int startIdentifier, int reserveAmount)
        throws ServiceException {
    try {
        SiteCodeAddedNotification notification = new SiteCodeAddedNotification();
        notification.setCreatedTime(new Date().toString());
        notification.setUsername(userName);
        notification.setNewCodesStartIdentifier(Integer.toString(startIdentifier));
        notification.setNofAddedCodes(Integer.toString(reserveAmount));
        notification.setNewCodesEndIdentifier(Integer.toString(startIdentifier + reserveAmount - 1));
        notification.setTotalNumberOfAvailableCodes(Integer.toString(siteCodeDao.getFeeSiteCodeAmount()));

        final String[] to;
        // if test e-mail is provided, then do not send notification to actual receivers
        if (!StringUtils.isEmpty(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO))) {
            notification.setTest(true);
            notification.setTo(Props.getRequiredProperty(PropsIF.SITE_CODE_RESERVE_NOTIFICATION_TO));
            to = StringUtils.split(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO), ",");
        } else {
            to = StringUtils.split(Props.getRequiredProperty(PropsIF.SITE_CODE_RESERVE_NOTIFICATION_TO), ",");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", notification);

        final String text = processTemplate("site_code_reservation.ftl", map);

        MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false);
                message.setText(text, false);
                message.setFrom(
                        new InternetAddress(Props.getRequiredProperty(PropsIF.SITE_CODE_NOTIFICATION_FROM)));
                message.setSubject("New site codes added");
                message.setTo(to);
            }
        };
        mailSender.send(mimeMessagePreparator);

    } catch (Exception e) {
        throw new ServiceException("Failed to send new site codes reservation notification: " + e.toString(),
                e);
    }
}

From source file:org.wallride.service.UserService.java

@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true)
public User updatePassword(PasswordUpdateRequest request, PasswordResetToken passwordResetToken) {
    User user = userRepository.findOneForUpdateById(request.getUserId());
    if (user == null) {
        throw new IllegalArgumentException("The user does not exist");
    }/*from ww w.j  ava2s  .c o  m*/
    PasswordEncoder passwordEncoder = new StandardPasswordEncoder();
    user.setLoginPassword(passwordEncoder.encode(request.getPassword()));
    user.setUpdatedAt(LocalDateTime.now());
    user.setUpdatedBy(passwordResetToken.getUser().toString());
    user = userRepository.saveAndFlush(user);

    passwordResetTokenRepository.delete(passwordResetToken);

    try {
        Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
        String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());

        ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
        if (blog.isMultiLanguage()) {
            builder.path("/{language}");
        }
        builder.path("/login");

        Map<String, Object> urlVariables = new LinkedHashMap<>();
        urlVariables.put("language", request.getLanguage());
        urlVariables.put("token", passwordResetToken.getToken());
        String loginLink = builder.buildAndExpand(urlVariables).toString();

        Context ctx = new Context(LocaleContextHolder.getLocale());
        ctx.setVariable("passwordResetToken", passwordResetToken);
        ctx.setVariable("resetLink", loginLink);

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
        message.setSubject(MessageFormat.format(
                messageSourceAccessor.getMessage("PasswordChangedSubject", LocaleContextHolder.getLocale()),
                blogTitle));
        message.setFrom(mailProperties.getProperties().get("mail.from"));
        message.setTo(passwordResetToken.getEmail());

        String htmlContent = templateEngine.process("password-changed", ctx);
        message.setText(htmlContent, true); // true = isHtml

        mailSender.send(mimeMessage);
    } catch (MessagingException e) {
        throw new ServiceException(e);
    }

    return user;
}

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:org.wallride.service.UserService.java

public PasswordResetToken createPasswordResetToken(PasswordResetTokenCreateRequest request) {
    User user = userRepository.findOneByEmail(request.getEmail());
    if (user == null) {
        throw new EmailNotFoundException();
    }//w  w w.  ja  v  a2  s . c o m

    LocalDateTime now = LocalDateTime.now();
    PasswordResetToken passwordResetToken = new PasswordResetToken();
    passwordResetToken.setUser(user);
    passwordResetToken.setEmail(user.getEmail());
    passwordResetToken.setExpiredAt(now.plusHours(24));
    passwordResetToken.setCreatedAt(now);
    passwordResetToken.setCreatedBy(user.toString());
    passwordResetToken.setUpdatedAt(now);
    passwordResetToken.setUpdatedBy(user.toString());
    passwordResetToken = passwordResetTokenRepository.saveAndFlush(passwordResetToken);

    try {
        Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
        String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());

        ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
        if (blog.isMultiLanguage()) {
            builder.path("/{language}");
        }
        builder.path("/password-reset");
        builder.path("/{token}");

        Map<String, Object> urlVariables = new LinkedHashMap<>();
        urlVariables.put("language", request.getLanguage());
        urlVariables.put("token", passwordResetToken.getToken());
        String resetLink = builder.buildAndExpand(urlVariables).toString();

        Context ctx = new Context(LocaleContextHolder.getLocale());
        ctx.setVariable("passwordResetToken", passwordResetToken);
        ctx.setVariable("resetLink", resetLink);

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
        message.setSubject(MessageFormat.format(
                messageSourceAccessor.getMessage("PasswordResetSubject", LocaleContextHolder.getLocale()),
                blogTitle));
        message.setFrom(mailProperties.getProperties().get("mail.from"));
        message.setTo(passwordResetToken.getEmail());

        String htmlContent = templateEngine.process("password-reset", ctx);
        message.setText(htmlContent, true); // true = isHtml

        mailSender.send(mimeMessage);
    } catch (MessagingException e) {
        throw new ServiceException(e);
    }

    return passwordResetToken;
}

From source file:org.wallride.service.UserService.java

@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true)
public List<UserInvitation> inviteUsers(UserInvitationCreateRequest form, BindingResult result,
        AuthorizedUser authorizedUser) throws MessagingException {
    String[] recipients = StringUtils.commaDelimitedListToStringArray(form.getInvitees());

    LocalDateTime now = LocalDateTime.now();

    List<UserInvitation> invitations = new ArrayList<>();
    for (String recipient : recipients) {
        UserInvitation invitation = new UserInvitation();
        invitation.setEmail(recipient);/*from   w  ww  . ja v a2s  . com*/
        invitation.setMessage(form.getMessage());
        invitation.setExpiredAt(now.plusHours(72));
        invitation.setCreatedAt(now);
        invitation.setCreatedBy(authorizedUser.toString());
        invitation.setUpdatedAt(now);
        invitation.setUpdatedBy(authorizedUser.toString());
        invitation = userInvitationRepository.saveAndFlush(invitation);
        invitations.add(invitation);
    }

    Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
    for (UserInvitation invitation : invitations) {
        String websiteTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());
        String signupLink = ServletUriComponentsBuilder.fromCurrentContextPath().path("/_admin/signup")
                .queryParam("token", invitation.getToken()).buildAndExpand().toString();

        final Context ctx = new Context(LocaleContextHolder.getLocale());
        ctx.setVariable("websiteTitle", websiteTitle);
        ctx.setVariable("authorizedUser", authorizedUser);
        ctx.setVariable("signupLink", signupLink);
        ctx.setVariable("invitation", invitation);

        final MimeMessage mimeMessage = mailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
        message.setSubject(MessageFormat.format(
                messageSourceAccessor.getMessage("InvitationMessageTitle", LocaleContextHolder.getLocale()),
                authorizedUser.toString(), websiteTitle));
        message.setFrom(authorizedUser.getEmail());
        message.setTo(invitation.getEmail());

        final String htmlContent = templateEngine.process("user-invite", ctx);
        message.setText(htmlContent, true); // true = isHtml

        mailSender.send(mimeMessage);
    }

    return invitations;
}

From source file:eionet.meta.service.EmailServiceImpl.java

/**
 * {@inheritDoc}//from   w w  w  . jav  a  2s.c  o  m
 */
@Override
public void notifySiteCodeAllocation(String country, AllocationResult allocationResult, boolean adminRole)
        throws ServiceException {
    try {
        SiteCodeAllocationNotification notification = new SiteCodeAllocationNotification();
        notification.setAllocationTime(allocationResult.getAllocationTime().toString());
        notification.setUsername(allocationResult.getUserName());
        notification.setCountry(country);
        notification.setNofAvailableCodes(Integer.toString(siteCodeDao.getFeeSiteCodeAmount()));
        notification.setTotalNofAllocatedCodes(
                Integer.toString(siteCodeDao.getCountryUnusedAllocations(country, false)));
        notification.setNofCodesAllocatedByEvent(Integer.toString(allocationResult.getAmount()));

        SiteCodeFilter filter = new SiteCodeFilter();
        filter.setDateAllocated(allocationResult.getAllocationTime());
        filter.setUserAllocated(allocationResult.getUserName());
        filter.setUsePaging(false);
        SiteCodeResult siteCodes = siteCodeDao.searchSiteCodes(filter);

        notification.setSiteCodes(siteCodes.getList());
        notification.setAdminRole(adminRole);

        final String[] to;
        // if test e-mail is provided, then do not send notification to actual receivers
        if (!StringUtils.isEmpty(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO))) {
            notification.setTest(true);
            notification.setTo(StringUtils.join(parseRoleAddresses(country), ","));
            to = StringUtils.split(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO), ",");
        } else {
            to = parseRoleAddresses(country);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", notification);

        final String text = processTemplate("site_code_allocation.ftl", map);

        MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false);
                message.setText(text, false);
                message.setFrom(
                        new InternetAddress(Props.getRequiredProperty(PropsIF.SITE_CODE_NOTIFICATION_FROM)));
                message.setSubject("Site codes allocated");
                message.setTo(to);
            }
        };
        mailSender.send(mimeMessagePreparator);

    } catch (Exception e) {
        throw new ServiceException("Failed to send allocation notification: " + e.toString(), e);
    }
}

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

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

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("vacaciones.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:mx.edu.um.mateo.rh.web.VacacionesEmpleadoController.java

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

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("vacacionesEmpleado.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);
}