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:net.triptech.metahive.service.EmailSenderService.java

/**
 * Send an email message using the configured Spring sender. On success
 * record the sent message in the datastore for reporting purposes
 *
 * @param email the email/*  w  ww . j  a  v a 2 s  .c  om*/
 * @param attachments the attachments
 * @throws ServiceException the service exception
 */
public final void send(final SimpleMailMessage email, TreeMap<String, Object> attachments)
        throws ServiceException {

    // Check to see whether the required fields are set (to, from, message)
    if (email.getTo() == null) {
        throw new ServiceException("Error sending email: Recipient " + "address required");
    }
    if (StringUtils.isBlank(email.getFrom())) {
        throw new ServiceException("Error sending email: Email requires " + "a from address");
    }
    if (StringUtils.isBlank(email.getText())) {
        throw new ServiceException("Error sending email: No email " + "message specified");
    }
    if (mailSender == null) {
        throw new ServiceException("The JavaMail sender has not " + "been configured");
    }

    // Prepare the email message
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = null;
    boolean htmlMessage = false;
    if (StringUtils.containsIgnoreCase(email.getText(), "<html")) {
        htmlMessage = true;
        try {
            helper = new MimeMessageHelper(message, true, "UTF-8");
        } catch (MessagingException me) {
            throw new ServiceException("Error preparing email for sending: " + me.getMessage());
        }
    } else {
        helper = new MimeMessageHelper(message);
    }

    try {
        helper.setTo(email.getTo());
        helper.setFrom(email.getFrom());
        helper.setSubject(email.getSubject());

        if (email.getCc() != null) {
            helper.setCc(email.getCc());
        }
        if (email.getBcc() != null) {
            helper.setBcc(email.getBcc());
        }

        if (htmlMessage) {
            String plainText = email.getText();
            try {
                ConvertHtmlToText htmlToText = new ConvertHtmlToText();
                plainText = htmlToText.convert(email.getText());
            } catch (Exception e) {
                logger.error("Error converting HTML to plain text: " + e.getMessage());
            }
            helper.setText(plainText, email.getText());
        } else {
            helper.setText(email.getText());
        }

        if (email.getSentDate() != null) {
            helper.setSentDate(email.getSentDate());
        } else {
            helper.setSentDate(Calendar.getInstance().getTime());
        }

    } catch (MessagingException me) {
        throw new ServiceException("Error preparing email for sending: " + me.getMessage());
    }

    // Append any attachments (if an HTML email)
    if (htmlMessage && attachments != null) {
        for (String id : attachments.keySet()) {
            Object reference = attachments.get(id);

            if (reference instanceof File) {
                try {
                    FileSystemResource res = new FileSystemResource((File) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    logger.error("Error appending File attachment: " + me.getMessage());
                }
            }
            if (reference instanceof URL) {
                try {
                    UrlResource res = new UrlResource((URL) reference);
                    helper.addInline(id, res);
                } catch (MessagingException me) {
                    logger.error("Error appending URL attachment: " + me.getMessage());
                }
            }
        }
    }

    // Send the email message
    try {
        mailSender.send(message);
    } catch (MailException me) {
        logger.error("Error sending email: " + me.getMessage());
        throw new ServiceException("Error sending email: " + me.getMessage());
    }
}

From source file:dk.nsi.haiba.epimibaimporter.email.EmailSender.java

private void sendText(final String subject, final String nonHtml) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        @Override//from   www.j  ava2 s  .  c om
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setValidateAddresses(true);

            String[] split = to_commaseparated.split(",");
            for (String emailAddress : split) {
                emailAddress = emailAddress.trim();
                try {
                    log.trace("adding " + emailAddress);
                    messageHelper.addTo(emailAddress);
                    log.trace("added " + emailAddress);
                } catch (MessagingException e) {
                    log.error("unable to parse email address from " + emailAddress, e);
                }
            }
            messageHelper.setFrom(from);
            messageHelper.setSubject(subject);
            messageHelper.setText(nonHtml, false);
        }
    };
    javaMailSender.send(preparator);
}

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

@RequestMapping(value = "/app", params = { "delete" })
public ModelAndView deleteApp(@RequestParam("delete") Long id, Authentication authentication) {
    UserDetails user = (UserDetails) authentication.getPrincipal();
    Developer developer = appManagement.getDeveloper(user.getUsername());

    log.debug("User {} deleted the app with id {}.", citizenLoggingUtil.getLogsafeSSN(user.getUsername()), id);

    if (developer == null) {
        return new ModelAndView("redirect:register_developer");
    } else {//from   w  ww  . j a  v a 2s.  c om
        Application application = appManagement.getApplication(id);
        log.debug("Deleting the app {}.", application.getName());

        if (application.getDeveloper().getResidentIdentificationNumber().equals(user.getUsername())) {
            appManagement.removeApplication(id);

            try {
                MimeMessage message = sender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message);

                helper.setTo(mailAddress);
                helper.setFrom(new InternetAddress(mailFrom));
                helper.setSubject("Borttagen app: " + application.getName());
                helper.setText("Utvecklare med personnr " + user.getUsername() + " har tagit bort appen: "
                        + application.getName());
                sender.send(message);
            } catch (Exception e) {
                log.error("Caught exception while trying to send email", e);
            }

        } else {
            throw new RuntimeException(
                    "The logged in user is not the same as the developer of the application!");
        }

        return new ModelAndView("redirect:");
    }
}

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

private void sendConfirmationEmail(final Event event, final Participant participant, final String baseUrl) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @SuppressWarnings(value = "unchecked")
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(participant.getEmail());
            message.setFrom(conf.getConfirmationSenderEmailAddress());
            message.setSubject("Please confirm event registration");
            Map model = new HashMap();
            model.put("participant", participant);
            model.put("event", event);
            model.put("baseUrl", baseUrl);
            model.put("confirmationCode", URLEncoder.encode(participant.getConfirmationCode(), "UTF-8"));
            model.put("email", URLEncoder.encode(participant.getEmail(), "UTF-8"));
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "it/jugpadova/registration-confirmation.vm", model);
            message.setText(text, true);
        }/*from   w ww.ja va  2 s.com*/
    };
    this.mailSender.send(preparator);
}

From source file:MailSender.java

public void send(Item item) {

    // major: well, sender is null, so no email is going out...silently. Just a debug message.
    // this means that the initial configuration is not able to create a sender.
    // This control should no be here and the methods that handle jndi or configFile should throw a
    // ConfigurationException if the sender is not created.
    if (sender == null) {
        logger.debug("mail sender is null, not sending notifications");
        return;//from w  w w.  j a v  a 2  s. c  o m
    }

    // TODO make this locale sensitive per recipient
    // major: don't use the comment to explain what the code is doing, just wrap the function in a
    // method with a talking name. This apply to all comments in this method.
    logger.debug("attempting to send mail for item update");
    // prepare message content
    StringBuffer sb = new StringBuffer();
    String anchor = getItemViewAnchor(item, defaultLocale);
    sb.append(anchor);
    // minor: why is not important here the user's locale like in the sendUserPassword method?
    sb.append(ItemUtils.getAsHtml(item, messageSource, defaultLocale));
    sb.append(anchor);
    if (logger.isDebugEnabled()) {
        logger.debug("html content: " + sb);
    }
    // prepare message
    MimeMessage message = sender.createMimeMessage();
    // minor: I would use StandardCharsets.UTF_8.name() that return the canonical name
    // major: how do you test the use cases about the message?
    // the message is in the local stack so it can't be tested
    // better to implement a bridge pattern to decouple the messageHelper and pass it as
    // a collaborator. Although keep in mind that building the message is not a responsibility
    // of this class so this class should just send the message and not building it.
    MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");

    // Remember the TO person email to prevent duplicate mails
    // minor: recipient would be a better name for this variable
    // major: catching a general Exception is a bad idea. You are telling me
    // we could have a problem but when I'm reading it and I don't understand
    // what could go wrong (and, also, the try block is too long so that's one of
    // the reason I can't see what could go wrong)
    String toPersonEmail;
    try {
        helper.setText(addHeaderAndFooter(sb), true);
        helper.setSubject(getSubject(item));
        helper.setSentDate(new Date());
        helper.setFrom(from);
        // set TO
        if (item.getAssignedTo() != null) {
            helper.setTo(item.getAssignedTo().getEmail());
            toPersonEmail = item.getAssignedTo().getEmail();
        } else {
            helper.setTo(item.getLoggedBy().getEmail());
            toPersonEmail = item.getLoggedBy().getEmail();
        }
        // set CC
        List<String> cclist = new ArrayList<String>();
        if (item.getItemUsers() != null) {
            for (ItemUser itemUser : item.getItemUsers()) {
                // Send only, if person is not the TO assignee
                if (!toPersonEmail.equals(itemUser.getUser().getEmail())) {
                    cclist.add(itemUser.getUser().getEmail());
                }
            }

            // sounds complicated but we have to ensure that no null
            // item will be set in setCC(). So we collect the cc items
            // in the cclist and transform it to an stringarray.
            if (cclist.size() > 0) {
                String[] cc = cclist.toArray(new String[0]);
                helper.setCc(cc);
            }
        }
        // send message
        // workaround: Some PSEUDO user has no email address. Because email
        // address
        // is mandatory, you can enter "no" in email address and the mail
        // will not
        // be sent.

        // major: this check is too late, we created everything and then we
        // won't use it.
        if (!"no".equals(toPersonEmail))
            sendInNewThread(message);
    } catch (Exception e) {
        logger.error("failed to prepare e-mail", e);
    }
}

From source file:com.logicaalternativa.ejemplomock.rest.sender.SendMailCodePromotionImp.java

private void sendEmail(final PromotionCode promotionCode, final Locale locale) throws MessagingException {

    MimeMessage mimeMessage = getJavaMailSender().createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

    final String subject = getMessageSource().getMessage("email.promotionCode.subject", new Object[] {},
            "email.promotionCode.subject", locale);

    final String to = (new StringBuilder())
            .append(promotionCode.getNameUser() != null ? promotionCode.getNameUser().toUpperCase() : "")
            .append("<").append(promotionCode.getEmail() != null ? promotionCode.getEmail() : "").append(">")
            .toString();//  ww  w  . j  a v  a  2s.  c o  m

    final String text = getMessageSource().getMessage("email.promotionCode.txt",
            new Object[] { promotionCode.getCode() }, "email.promotionCode.txt", locale);

    final String html = getMessageSource().getMessage("email.promotionCode.html",
            new Object[] { promotionCode.getCode() }, "email.promotionCode.html", locale);

    helper.setFrom(getFrom());
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(text, html);

    getJavaMailSender().send(mimeMessage);

}

From source file:com.seer.datacruncher.utils.mail.MailService.java

public void sendMail(MailConfig mailConfig) throws Exception {
    String logMsg = "MailService:sendMail():";
    InputStream attachment = null;
    MimeMessage mimeMessage = null;//w w  w. j a v  a  2s .  com
    MimeMessageHelper helper = null;
    try {
        mimeMessage = mailSender.createMimeMessage();
        helper = new MimeMessageHelper(mimeMessage, true);
        helper.setText(mailConfig.getText(), true);
        if (StringUtils.isEmpty(mailConfig.getMailTo())) {
            log.error("Invalid or empty 'toAddress' configured!!");
            throw new Exception("Invalid or empty 'toAddress' configured");
        }
        if (StringUtils.isEmpty(mailConfig.getMailFrom())) {
            log.error("Invalid or empty 'FromAddress' configured!!");
            throw new Exception("Invalid or empty 'FromAddress' configured");
        }
        if (!isEmailValid(mailConfig.getMailFrom())) {
            log.error("Invalid 'FromAddress' configured!!");
            throw new Exception("Invalid 'FromAddress' configured");
        }
        helper.setFrom(new InternetAddress(mailConfig.getMailFrom()));
        helper.setSubject(mailConfig.getSubject());
        helper.setTo(getToAddress(mailConfig.getMailTo()));
        attachment = mailConfig.getAttachment();
        if (attachment != null) {
            StreamAttachmentDataSource datasource = new StreamAttachmentDataSource(mailConfig.getAttachment());
            helper.addAttachment(mailConfig.getAttachmentName(), datasource);
        }
        this.mailSender.send(mimeMessage);

    } catch (AuthenticationFailedException afex) {
        log.error(logMsg + "AuthenticationFailedException:", afex);
        throw new Exception("AuthenticationFailedException", afex);
    } catch (MessagingException mex) {
        log.error(logMsg + "Exception:", mex);
        throw new Exception("MessagingException", mex);
    } catch (Exception ex) {
        log.error(logMsg + "Exception:", ex);
        throw ex;
    }
}

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

@RequestMapping(value = "/app", method = RequestMethod.POST)
public String registerApp(ModelMap model, @ModelAttribute("application") Application application,
        @RequestParam("certificate") MultipartFile certificate, MultipartFile icon, BindingResult result,
        Authentication authentication) throws IOException {
    UserDetails user = (UserDetails) authentication.getPrincipal();
    Developer developer = appManagement.getDeveloper(user.getUsername());

    log.debug("User {} registered or edited the app {}.", citizenLoggingUtil.getLogsafeSSN(user.getUsername()),
            application.getName());/*from   w  ww  .  j  av  a2  s  . co  m*/

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

        applicationValidator.validate(application, result);

        application.setRegistrationDate(new Date());
        application.setState(State.REGISTRATED);

        application.setDeveloper(developer);

        Application existingApp = appManagement.getApplicationByClientId(application.getClientId());

        if (existingApp != null) {
            result.rejectValue("clientId", "invalid.clientId",
                    "Klient id:et finns redan registrerat, var god vlj ett annat.");
        }

        // validate icon if it exists
        if (application.getIcon() != null && application.getIcon().length > 0) {
            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");
            }
        }

        //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));
        }

        if (result.hasErrors()) {
            List<Permission> permissions = permissionServices.getAllPermissions();
            model.addAttribute("scopes", permissions);
            return "register_application";
        }

        Application savedApp = appManagement.registerApplication(application);

        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 "redirect:";
    }
}

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) {/*from   w  w w .  jav 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");
}