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

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

Introduction

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

Prototype

public MimeMessageHelper(MimeMessage mimeMessage) 

Source Link

Document

Create a new MimeMessageHelper for the given MimeMessage, assuming a simple text message (no multipart content, i.e.

Usage

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

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

    try {// w  w  w .j a va2  s  .  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);//w  w w  .  j  a v a2 s . c  o  m
    //helper.setFrom(messageSource.getMessage("registration.email.from", null, RequestContextUtils.getLocale(request)));
    message.setSubject(subject);
    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);//from   ww  w . ja  va  2  s  .  c om
    //helper.setFrom(messageSource.getMessage("registration.email.from", null, RequestContextUtils.getLocale(request)));
    message.setSubject(subject);
    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:br.com.s2it.snakes.controllers.CarController.java

@RequestMapping("/email")
public void email() {
    try {/*ww  w  .j av  a2  s .c o  m*/
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage);

        mailMsg.setFrom("snakeshackathon@gmail.com");
        mailMsg.setTo("daniel@balieiro.com");
        mailMsg.setSubject("Test mail");
        mailMsg.setText("Hello World!");

        mailSender.send(mimeMessage);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

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

    try {// w w  w. j  a va  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:business.services.MailService.java

public void notifyHubuser(User hubUser, List<LabRequestRepresentation> labRequests) {
    if (!hubUser.isHubUser()) {
        log.warn("The user is no hub user: " + hubUser.getUsername());
        return;// ww  w  . j  a  v a  2  s .co  m
    }
    List<String> codes = new ArrayList<>();
    List<String> snippets = new ArrayList<>();
    for (LabRequestRepresentation labRequest : labRequests) {
        codes.add(labRequest.getLabRequestCode());
        String link = getLink("/#/lab-request/view/" + labRequest.getId());
        String snippet = String.format(hubUserNotificationLabSnippet, link, // %1
                labRequest.getLabRequestCode(), // %2
                labRequest.getRequest().getTitle(), // %3
                labRequest.getLab().getNumber(), // %4
                labRequest.getLab().getName(), // %5
                labRequest.getRequesterName(), // %6
                labRequest.getRequest().getPathologistName() == null ? ""
                        : labRequest.getRequest().getPathologistName(), // %7
                labRequest.getRequesterLab().getNumber(), // %8
                labRequest.getRequesterLab().getName() // %9
        );
        snippets.add(snippet);
    }
    String labRequestCodes = String.join(", ", codes);
    String labRequestSnippets = String.join("\n", snippets);

    log.info("Notify hub user " + hubUser.getUsername() + " for lab requests " + labRequestCodes + ".");

    if (hubUser.getContactData() == null || hubUser.getContactData().getEmail() == null
            || hubUser.getContactData().getEmail().trim().isEmpty()) {
        log.warn("No email address set for hub user " + hubUser.getUsername());
        return;
    }
    log.info("Sending notification to " + hubUser.getContactData().getEmail());
    try {
        MimeMessageHelper message = new MimeMessageHelper(mailSender.createMimeMessage());
        message.setTo(hubUser.getContactData().getEmail());
        message.setFrom(getFrom(), fromName);
        message.setReplyTo(replyAddress, replyName);
        message.setSubject(
                String.format("PALGA-verzoek aan laboratoria, aanvraagnummers: %s", labRequestCodes));
        String body = String.format(hubUserNotificationTemplate, labRequestSnippets /* %1 */);
        message.setText(body);
        mailSender.send(message.getMimeMessage());
    } catch (MessagingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    }
}

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

protected MimeMessage createMimeMessage(String from, String to, String subject, String emailBody)
        throws MailException {
    try {/* ww w.j ava 2  s.co  m*/
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
        message.setFrom(from);
        // message.setContent("text/html");
        message.setTo(to);
        message.setSubject(subject);
        message.setText(emailBody, true);
        log.debug("Message " + message);
        return mimeMessage;
    } catch (MessagingException e) {// rethrow as MailException
        throw new MailPreparationException(e.getMessage(), e);
    }
}

From source file:business.services.MailService.java

public void sendActivationEmail(@NotNull ActivationLink link) {
    // Send email to user
    try {// ww  w .j a  va  2 s. c  o  m
        MimeMessageHelper message = new MimeMessageHelper(mailSender.createMimeMessage());
        String recipient = link.getUser().getUsername();
        message.setTo(recipient);
        message.setFrom(getFrom(), fromName);
        message.setReplyTo(replyAddress, replyName);
        message.setSubject("PALGA-account activeren / Activate PALGA account");
        String activationLink = getLink("/#/activate/" + link.getToken());
        message.setText(String.format(activationEmailTemplate, activationLink));
        mailSender.send(message.getMimeMessage());
        log.info("Activation link token generated for " + recipient + ": " + link.getToken());
    } catch (MessagingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    }
}

From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public ModelAndView editApp(ModelMap model, Authentication authentication,
        @ModelAttribute("application") Application application, MultipartFile icon,
        @RequestParam(value = "certificate", required = false) MultipartFile certificate,
        BindingResult result) {/* w  w  w  .  j  a  v  a 2  s. c om*/
    UserDetails user = (UserDetails) authentication.getPrincipal();
    Developer developer = appManagement.getDeveloper(user.getUsername());
    List<Permission> permissions = permissionServices.getAllPermissions();

    log.debug("User {} registered or edited the app {}.", citizenLoggingUtil.getLogsafeSSN(user.getUsername()),
            application.getName());

    if (developer == null) {
        return new ModelAndView("redirect:register_developer");
    } else {

        applicationValidator.validate(application, result);

        log.info("app id: " + application.getId());
        Application dbApp = appManagement.getApplication(application.getId());

        if (!user.getUsername().equals(dbApp.getDeveloper().getResidentIdentificationNumber())) {
            throw new IllegalArgumentException(
                    "The application developer is not the same as the logged in user");
        }

        if (application.getIcon() == null && dbApp.getIcon() != null && dbApp.getIcon().length > 0) {
            application.setIcon(dbApp.getIcon());
            log.debug("Icon wasn't updated this time around");
        } else if (application.getIcon() != null) {
            log.debug("Icon was updated");
            try {
                ByteArrayInputStream bis = new ByteArrayInputStream(application.getIcon());
                BufferedImage bufferedImage = ImageIO.read(bis);
                log.info("Width: " + bufferedImage.getWidth() + " Height: " + bufferedImage.getHeight());
                application.setIconContentType(icon.getContentType());
                // TODO: Check width and height here!
            } catch (Exception e) {
                result.rejectValue("icon", "invalid.icon", "Ikonen r ej giltig");
            }
        }

        application.setCertificates(dbApp.getCertificates());
        application.setRegistrationDate(dbApp.getRegistrationDate());
        application.setState(dbApp.getState());
        application.setDeveloper(developer);

        //For now we are just allowing the addition of just one certificate
        List<Certificate> certs = new ArrayList<>();

        if (certificate != null && certificate.getSize() > 0) {
            certs.add(createCertificate(certificate, result));
        }

        //Error handling
        if (result.hasErrors()) {
            model.addAttribute(application);
            model.addAttribute("scopes", permissions);
            return new ModelAndView("application/edit");
        }

        Application savedApp = appManagement.updateApplication(application);

        //Remove everything old.
        // Just allow one certificate to be set right now even though the model allows for more.
        //If this behavior is unwanted the GUI has to adapt for this as well as it only caters
        //for on certificate right now.
        if (certificate != null && certificate.getSize() > 0) {
            Set<Certificate> oldCerts = new HashSet<>();

            //Clone in order to not get a concurrent modification exception
            for (Certificate cert : savedApp.getCertificates()) {
                oldCerts.add(cert);
            }

            //Remove anything old
            for (Certificate cert : oldCerts) {
                cert.setApplication(null);
                savedApp.getCertificates().remove(cert);
                appManagement.removeCertificate(cert);
            }

            //Set the new Certificate
            for (Certificate cert : certs) {
                cert.setApplication(savedApp);
                appManagement.saveCertificate(cert);
                savedApp.getCertificates().add(cert);
            }
        }

        try {
            log.debug("Composing message to: {}", mailAddress);
            MimeMessage message = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);

            helper.setTo(mailAddress);
            helper.setFrom(new InternetAddress(mailFrom));

            log.debug("Creating message for existing app. User {} edited the app {}",
                    citizenLoggingUtil.getLogsafeSSN(user.getUsername()), application.getName());
            helper.setSubject("Redigerad app: " + application.getName());
            helper.setText("Utvecklare med personnr " + user.getUsername() + " har redigerat appen: "
                    + application.getName());

            log.debug("Sending mail notification.");
            sender.send(message);
        } catch (Exception e) {
            log.error("Caught exception while trying to send email", e);
        }
    }
    return new ModelAndView("redirect:/developer");
}

From source file:business.services.MailService.java

public void sendPasswordRecoveryToken(NewPasswordRequest npr) {
    try {//from  ww w.  j a  v  a  2s. c  o  m
        MimeMessageHelper message = new MimeMessageHelper(mailSender.createMimeMessage());
        String recipient = npr.getUser().getContactData().getEmail();
        message.setTo(recipient);
        message.setFrom(getFrom(), fromName);
        message.setReplyTo(replyAddress, replyName);
        message.setSubject(passwordRecoverySubject);
        String passwordRecoveryLink = getLink("/#/login/reset-password/" + npr.getToken());
        message.setText(String.format(passwordRecoveryTemplate, passwordRecoveryLink));
        log.info("Sending password recovery token to " + recipient + ".");
        mailSender.send(message.getMimeMessage());
    } catch (MessagingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage());
        throw new EmailError("Email error: " + e.getMessage());
    }
}