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

public PasswordResetToken createPasswordResetToken(PasswordResetTokenCreateRequest request) {
    User user = userRepository.findOneByEmail(request.getEmail());
    if (user == null) {
        throw new EmailNotFoundException();
    }//from   w  w  w.j a  v  a  2  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  ww  w .jav a2  s  .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:gr.abiss.calipso.mail.MailSender.java

/**
 * /*from  ww w.jav  a 2  s  . c  o  m*/
 * @param email
 * @param subject
 * @param messageBody
 * @param attachments
 * @param encryption
 * @param keyStorePath
 */
public void send(String email, String subject, String messageBody, Map<String, DataSource> attachments,
        boolean html) {
    // prepare message
    try {
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        if (html) {
            helper.setText(addHeaderAndFooter(messageBody), true);
        } else {
            helper.setText(messageBody, false);
        }
        helper.setSubject(subject);
        helper.setSentDate(new Date());
        helper.setFrom(from);
        // set TO
        helper.setTo(email);
        if (MapUtils.isNotEmpty(attachments)) {
            for (String attachmentFilename : attachments.keySet()) {
                DataSource in = attachments.get(attachmentFilename);
                if (in != null) {
                    helper.addAttachment(attachmentFilename, in);
                }
            }
        }

        //logger.info("Sending email: "+subject+"\n"+messageBody);
        sendInNewThread(message);
    } catch (Exception e) {
        logger.error("failed to prepare e-mail", e);
    }
}

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  ava 2  s  . c o m*/
    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:com.gendevs.bedrock.appengine.integration.mail.Mailer.java

public void sendMail(Mail mail, Map<String, Object> model) throws MessagingException {

    //TODO: Deepak. not the perfect way to pull resources from the below code
    //but accordng to http://velocity.apache.org/engine/releases/velocity-1.7/developer-guide.html#resourceloaders
    //File resource handelers needs more config for which we don't have enough time.
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false, "utf-8");

    helper.setSubject(mail.getSubject());
    helper.setFrom(AppConstants.APP_EMAILID);

    for (MailReceiver mailReceiver : mail.getReceivers()) {
        model.put("_receiverFirstName", mailReceiver.firstName);
        model.put("_receiverLastName", mailReceiver.lastName);
        model.put("_receiverEmail", mailReceiver.email);
        model.put("_receiverImageUrl", mailReceiver.imageUrl);

        String mailBody = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                "com/gendevs/bedrock/appengine/integration/mail/templates/" + mail.getTemplateName(), "UTF-8",
                model);//from  w ww  .  java 2  s.c  o  m
        mimeMessage.setContent(mailBody, mail.getContentType());

        helper.setTo(mailReceiver.email);
        mailSender.send(mimeMessage);
    }
}

From source file:com.glaf.mail.MailSenderImpl.java

public void send(JavaMailSender javaMailSender, MailMessage mailMessage) throws Exception {
    if (StringUtils.isEmpty(mailMessage.getMessageId())) {
        mailMessage.setMessageId(UUID32.getUUID());
    }/*from   w  w w  . ja  v a2  s  .  c  o  m*/

    mailHelper = new MxMailHelper();
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();

    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

    if (StringUtils.isNotEmpty(mailMessage.getFrom())) {
        messageHelper.setFrom(mailMessage.getFrom());
        mailFrom = mailMessage.getFrom();
    } else {
        if (StringUtils.isEmpty(mailFrom)) {
            mailFrom = MailProperties.getString("mail.mailFrom");
        }
        messageHelper.setFrom(mailFrom);
    }

    logger.debug("mailFrom:" + mailFrom);

    if (mailMessage.getTo() != null) {
        messageHelper.setTo(mailMessage.getTo());
    }

    if (mailMessage.getCc() != null) {
        messageHelper.setCc(mailMessage.getCc());
    }

    if (mailMessage.getBcc() != null) {
        messageHelper.setBcc(mailMessage.getBcc());
    }

    if (mailMessage.getReplyTo() != null) {
        messageHelper.setReplyTo(mailMessage.getReplyTo());
    }

    String mailSubject = mailMessage.getSubject();
    if (mailSubject == null) {
        mailSubject = "";
    }

    if (mailSubject != null) {
        // mailSubject = MimeUtility.encodeText(new
        // String(mailSubject.getBytes(), encoding), encoding, "B");
        mailSubject = MimeUtility.encodeWord(mailSubject);
    }

    mimeMessage.setSubject(mailSubject);

    Map<String, Object> dataMap = mailMessage.getDataMap();
    if (dataMap == null) {
        dataMap = new java.util.HashMap<String, Object>();
    }

    String serviceUrl = SystemConfig.getServiceUrl();

    logger.debug("mailSubject:" + mailSubject);
    logger.debug("serviceUrl:" + serviceUrl);

    if (serviceUrl != null) {
        String loginUrl = serviceUrl + "/mx/login";
        String mainUrl = serviceUrl + "/mx/main";
        logger.debug("loginUrl:" + loginUrl);
        dataMap.put("loginUrl", loginUrl);
        dataMap.put("mainUrl", mainUrl);
    }

    mailMessage.setDataMap(dataMap);

    if (StringUtils.isEmpty(mailMessage.getContent())) {
        Template template = TemplateContainer.getContainer().getTemplate(mailMessage.getTemplateId());
        if (template != null) {
            String templateType = template.getTemplateType();
            logger.debug("templateType:" + templateType);
            // logger.debug("content:" + template.getContent());
            if (StringUtils.equals(templateType, "eml")) {
                if (template.getContent() != null) {
                    Mail m = mailHelper.getMail(template.getContent().getBytes());
                    String content = m.getContent();
                    if (StringUtils.isNotEmpty(content)) {
                        template.setContent(content);
                        try {
                            Writer writer = new StringWriter();
                            TemplateUtils.evaluate(mailMessage.getTemplateId(), dataMap, writer);
                            String text = writer.toString();
                            writer.close();
                            writer = null;
                            mailMessage.setContent(text);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            throw new RuntimeException(ex);
                        }
                    }
                }
            } else {
                try {
                    String text = TemplateUtils.process(dataMap, template.getContent());
                    mailMessage.setContent(text);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    if (StringUtils.isNotEmpty(mailMessage.getContent())) {
        String text = mailMessage.getContent();
        if (StringUtils.isNotEmpty(callbackUrl)) {
            String href = callbackUrl + "?messageId=" + mailMessage.getMessageId();
            text = mailHelper.embedCallbackScript(text, href);
            mailMessage.setContent(text);
            logger.debug(text);
            messageHelper.setText(text, true);
        }
        messageHelper.setText(text, true);
    }

    logger.debug("mail body:" + mailMessage.getContent());

    Collection<Object> files = mailMessage.getFiles();

    if (files != null && !files.isEmpty()) {
        Iterator<Object> iterator = files.iterator();
        while (iterator.hasNext()) {
            Object object = iterator.next();
            if (object instanceof java.io.File) {
                java.io.File file = (java.io.File) object;
                FileSystemResource resource = new FileSystemResource(file);
                String name = file.getName();
                name = MailTools.chineseStringToAscii(name);
                messageHelper.addAttachment(name, resource);
                logger.debug("add attachment:" + name);
            } else if (object instanceof DataSource) {
                DataSource dataSource = (DataSource) object;
                String name = dataSource.getName();
                name = MailTools.chineseStringToAscii(name);
                messageHelper.addAttachment(name, dataSource);
                logger.debug("add attachment:" + name);
            } else if (object instanceof DataFile) {
                DataFile dataFile = (DataFile) object;
                if (StringUtils.isNotEmpty(dataFile.getFilename())) {
                    String name = dataFile.getFilename();
                    name = MailTools.chineseStringToAscii(name);
                    InputStreamSource inputStreamSource = new MxMailInputSource(dataFile);
                    messageHelper.addAttachment(name, inputStreamSource);
                    logger.debug("add attachment:" + name);
                }
            }
        }
    }

    mimeMessage.setSentDate(new java.util.Date());

    javaMailSender.send(mimeMessage);

    logger.info("-----------------------------------------");
    logger.info("????");
    logger.info("-----------------------------------------");
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobAlertImpl.java

public void sendAlertMail(Job job, ReportJob jobDetails, List<ExceptionInfo> exceptions,
        JavaMailSender mailSender, String fromAddress, String[] toAddresses, String characterEncoding)
        throws JobExecutionException {
    ReportJobAlert alert = jobDetails.getAlert();
    boolean isSucceed = exceptions.isEmpty();
    switch (alert.getJobState()) {
    case FAIL_ONLY:
        if (isSucceed)
            return;
        break;/*  w w  w. j  av  a 2  s.c  om*/
    case SUCCESS_ONLY:
        if (!isSucceed)
            return;
        break;
    case NONE:
        return;
    }
    if (alert != null) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, characterEncoding);
            messageHelper.setFrom(fromAddress);
            String subject = alert.getSubject();
            if ((subject == null) && (job instanceof ReportExecutionJob))
                subject = ((ReportExecutionJob) job).getMessage("report.scheduling.job.default.alert.subject",
                        null);
            messageHelper.setSubject(subject);

            StringBuffer messageText = new StringBuffer();

            String text = (isSucceed ? alert.getMessageText() : alert.getMessageTextWhenJobFails());
            if (text != null) {
                messageText.append(text);
            }
            messageHelper.setTo(toAddresses);

            if (alert.isIncludingReportJobInfo()) {
                messageText.append("\n");
                messageText.append("ReportJob Info:").append("\n");
                messageText.append("Label = ").append(jobDetails.getLabel()).append("\n");
                messageText.append("ID = ").append(jobDetails.getId()).append("\n");
                messageText.append("Description = ").append(jobDetails.getDescription()).append("\n");
                messageText.append("Status = ").append(exceptions.isEmpty() ? "PASS" : "FAIL").append("\n");
            }

            if (alert.isIncludingStackTrace()) {
                if (!exceptions.isEmpty()) {
                    for (Iterator it = exceptions.iterator(); it.hasNext();) {
                        ExceptionInfo exception = (ExceptionInfo) it.next();

                        messageText.append("\n");
                        messageText.append(exception.getMessage());

                        attachException(messageHelper, exception);
                    }
                }
            }
            messageHelper.setText(messageText.toString());
            mailSender.send(message);
        } catch (MessagingException e) {
            log.error("Error while sending report job alert notification", e);
            throw new JSExceptionWrapper(e);
        }
    }
}

From source file:alfio.manager.system.SmtpMailer.java

@Override
public void send(Event event, String to, List<String> cc, String subject, String text, Optional<String> html,
        Attachment... attachments) {/*from   w  w  w . j a v  a  2  s .  c o m*/
    MimeMessagePreparator preparator = (mimeMessage) -> {
        MimeMessageHelper message = html.isPresent() || !ArrayUtils.isEmpty(attachments)
                ? new MimeMessageHelper(mimeMessage, true, "UTF-8")
                : new MimeMessageHelper(mimeMessage, "UTF-8");
        message.setSubject(subject);
        message.setFrom(
                configurationManager.getRequiredValue(
                        Configuration.from(event.getOrganizationId(), event.getId(), SMTP_FROM_EMAIL)),
                event.getDisplayName());
        String replyTo = configurationManager.getStringConfigValue(
                Configuration.from(event.getOrganizationId(), event.getId(), MAIL_REPLY_TO), "");
        if (StringUtils.isNotBlank(replyTo)) {
            message.setReplyTo(replyTo);
        }
        message.setTo(to);
        if (cc != null && !cc.isEmpty()) {
            message.setCc(cc.toArray(new String[cc.size()]));
        }
        if (html.isPresent()) {
            message.setText(text, html.get());
        } else {
            message.setText(text, false);
        }

        if (attachments != null) {
            for (Attachment a : attachments) {
                message.addAttachment(a.getFilename(), new ByteArrayResource(a.getSource()),
                        a.getContentType());
            }
        }

        message.getMimeMessage().saveChanges();
        message.getMimeMessage().removeHeader("Message-ID");
    };
    toMailSender(event).send(preparator);
}

From source file:org.jresponder.message.MessageRefImpl.java

/**
 * Render a message in the context of a particular subscriber
 * and subscription.// w ww.j  a v  a 2 s .  c  om
 */
@Override
public boolean populateMessage(MimeMessage aMimeMessage, SendConfig aSendConfig, Subscriber aSubscriber,
        Subscription aSubscription) {

    try {

        // prepare context
        Map<String, Object> myRenderContext = new HashMap<String, Object>();
        myRenderContext.put("subscriber", aSubscriber);
        myRenderContext.put("subscription", aSubscription);
        myRenderContext.put("config", aSendConfig);
        myRenderContext.put("message", this);

        // render the whole file
        String myRenderedFileContents = TextRenderUtil.getInstance().render(fileContents, myRenderContext);

        // now parse again with Jsoup
        Document myDocument = Jsoup.parse(myRenderedFileContents);

        String myHtmlBody = "";
        String myTextBody = "";

        // html body
        Elements myBodyElements = myDocument.select("#htmlbody");
        if (!myBodyElements.isEmpty()) {
            myHtmlBody = myBodyElements.html();
        }

        // text body
        Elements myJrTextBodyElements = myDocument.select("#textbody");
        if (!myJrTextBodyElements.isEmpty()) {
            myTextBody = TextUtil.getInstance().getWholeText(myJrTextBodyElements.first());
        }

        // now build the actual message
        MimeMessage myMimeMessage = aMimeMessage;
        // wrap it in a MimeMessageHelper - since some things are easier with that
        MimeMessageHelper myMimeMessageHelper = new MimeMessageHelper(myMimeMessage);

        // set headers

        // subject
        myMimeMessageHelper.setSubject(TextRenderUtil.getInstance()
                .render((String) propMap.get(MessageRefProp.JR_SUBJECT.toString()), myRenderContext));

        // TODO: implement DKIM, figure out subetha

        String mySenderEmailPattern = aSendConfig.getSenderEmailPattern();
        String mySenderEmail = TextRenderUtil.getInstance().render(mySenderEmailPattern, myRenderContext);
        myMimeMessage.setSender(new InternetAddress(mySenderEmail));

        myMimeMessageHelper.setTo(aSubscriber.getEmail());

        // from
        myMimeMessageHelper.setFrom(
                TextRenderUtil.getInstance()
                        .render((String) propMap.get(MessageRefProp.JR_FROM_EMAIL.toString()), myRenderContext),
                TextRenderUtil.getInstance()
                        .render((String) propMap.get(MessageRefProp.JR_FROM_NAME.toString()), myRenderContext));

        // see how to set body

        // if we have both text and html, then do multipart
        if (myTextBody.trim().length() > 0 && myHtmlBody.trim().length() > 0) {

            // create wrapper multipart/alternative part
            MimeMultipart ma = new MimeMultipart("alternative");
            myMimeMessage.setContent(ma);
            // create the plain text
            BodyPart plainText = new MimeBodyPart();
            plainText.setText(myTextBody);
            ma.addBodyPart(plainText);
            // create the html part
            BodyPart html = new MimeBodyPart();
            html.setContent(myHtmlBody, "text/html");
            ma.addBodyPart(html);
        }

        // if only HTML, then just use that
        else if (myHtmlBody.trim().length() > 0) {
            myMimeMessageHelper.setText(myHtmlBody, true);
        }

        // if only text, then just use that
        else if (myTextBody.trim().length() > 0) {
            myMimeMessageHelper.setText(myTextBody, false);
        }

        // if neither text nor HTML, then the message is being skipped,
        // so we just return null
        else {
            return false;
        }

        return true;

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(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();/*from  w  w w  .  j  a  v a 2 s  .  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);

}