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, int multipartMode) throws MessagingException 

Source Link

Document

Create a new MimeMessageHelper for the given MimeMessage, in multipart mode (supporting alternative texts, inline elements and attachments) if requested.

Usage

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

/**
 * {@inheritDoc}/*from  w  w w  .  j av  a  2  s.c om*/
 */
@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:gov.nih.nci.cabig.caaers.tools.mail.CaaersJavaMailSender.java

/**
 * This method is used to send an email//from   w  w w  .j  av a  2s. c  om
 */
public void sendMail(String[] to, String[] cc, String subject, String content, String[] attachmentFilePaths) {
    if (to == null || to.length == 0 || to[0] == null) {
        return;
    }
    try {
        MimeMessage message = createMimeMessage();
        message.setSubject(subject);

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        if (cc != null && cc.length > 0) {
            helper.setCc(cc);
        }
        helper.setText(content);

        for (String attachmentPath : attachmentFilePaths) {
            if (StringUtils.isNotEmpty(attachmentPath)) {
                File f = new File(attachmentPath);
                FileSystemResource file = new FileSystemResource(f);
                helper.addAttachment(file.getFilename(), file);
            }
        }
        send(message);

    } catch (Exception e) {
        if (SUPRESS_MAIL_SEND_EXCEPTION)
            return; //supress the excetion related to email sending
        throw new CaaersSystemException("Error while sending email to " + to[0], e);
    }
}

From source file:edu.unc.lib.dl.services.MailNotifier.java

public void sendIngestSuccessNotice(IngestProperties props, int ingestedCount) {
    String html = null, text = null;
    boolean logEmail = true;
    MimeMessage mimeMessage = null;/*from  w  w  w  . ja v a 2 s .  c  o m*/
    try {
        Template htmlTemplate = this.freemarkerConfiguration.getTemplate("IngestSuccessHtml.ftl",
                Locale.getDefault(), "utf-8");
        Template textTemplate = this.freemarkerConfiguration.getTemplate("IngestSuccessText.ftl",
                Locale.getDefault(), "utf-8");

        // put data into the model
        HashMap<String, Object> model = new HashMap<String, Object>();
        model.put("numberOfObjects", new Integer(ingestedCount));
        model.put("irBaseUrl", this.irBaseUrl);
        List tops = new ArrayList();
        for (ContainerPlacement p : props.getContainerPlacements().values()) {
            HashMap om = new HashMap();
            om.put("pid", p.pid.getPid());
            om.put("label", p.label);
            tops.add(om);
        }
        model.put("tops", tops);

        StringWriter sw = new StringWriter();
        htmlTemplate.process(model, sw);
        html = sw.toString();
        sw = new StringWriter();
        textTemplate.process(model, sw);
        text = sw.toString();
    } catch (IOException e1) {
        throw new Error("Unable to load email template for Ingest Success", e1);
    } catch (TemplateException e) {
        throw new Error("There was a problem loading FreeMarker templates for email notification", e);
    }

    try {
        if (log.isDebugEnabled() && this.mailSender instanceof JavaMailSenderImpl) {
            ((JavaMailSenderImpl) this.mailSender).getSession().setDebug(true);
        }
        mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED);

        for (String addy : props.getEmailRecipients()) {
            message.addTo(addy);
        }
        message.setSubject("CDR ingest complete");

        message.setFrom(this.getRepositoryFromAddress());
        message.setText(text, html);

        // attach Events XML
        // Document events = new Document(aip.getEventLogger().getAllEvents());
        // message.addAttachment("events.xml", new JDOMStreamSource(events));
        this.mailSender.send(mimeMessage);
        logEmail = false;
    } catch (MessagingException e) {
        log.error("Unable to send ingest success email.", e);
    } catch (RuntimeException e) {
        log.error(e);
    } finally {
        if (mimeMessage != null && logEmail) {
            try {
                mimeMessage.writeTo(System.out);
            } catch (Exception e) {
                log.error("Could not log email message after error.", e);
            }
        }
    }

}

From source file:info.jtrac.mail.MailSender.java

public void send(Item item) {
    if (sender == null) {
        logger.debug("mail sender is null, not sending notifications");
        return;/*from  w ww. ja v a  2 s  .c o  m*/
    }
    // TODO make this locale sensitive per recipient        
    logger.debug("attempting to send mail for item update");
    // prepare message content
    StringBuffer sb = new StringBuffer();
    String anchor = getItemViewAnchor(item, defaultLocale);
    sb.append(anchor);
    sb.append(ItemUtils.getAsHtml(item, messageSource, defaultLocale));
    sb.append(anchor);
    if (logger.isDebugEnabled()) {
        logger.debug("html content: " + sb);
    }
    // prepare message
    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");
    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());
        } else {
            helper.setTo(item.getLoggedBy().getEmail());
        }
        // set CC
        if (item.getItemUsers() != null) {
            String[] cc = new String[item.getItemUsers().size()];
            int i = 0;
            for (ItemUser itemUser : item.getItemUsers()) {
                cc[i++] = itemUser.getUser().getEmail();
            }
            helper.setCc(cc);
        }
        // send message
        sendInNewThread(message);
    } catch (Exception e) {
        logger.error("failed to prepare e-mail", e);
    }
}

From source file:com.marc.lastweek.business.services.mail.impl.MailServiceImpl.java

private MimeMessagePreparator getMimeMessagePreparator(final Locale locale, final String templateName,
        final Map<String, Object> templateData, final String mailTo) {

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

            // Set message attributes
            message.setTo(mailTo);// w w  w  .  j  a v  a 2  s.c om
            message.setFrom(MailServiceImpl.this.from);
            message.setSubject(getMailMessageEntry(locale, templateName + FIELD_SUBJECT));

            // Add parameters
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("locale", locale);
            model.put("dateTool", new DateTool());
            model.put("resourceTool", new ResourceTool());

            // Insert data in the template
            for (String name : templateData.keySet()) {
                model.put(name, templateData.get(name));
            }

            String text = VelocityEngineUtils.mergeTemplateIntoString(MailServiceImpl.this.velocityEngine,
                    MailServiceImpl.this.velocityTemplates.get(templateName), CHARSET, model);
            message.setText(text, true);

            // Insert stylesheet
            //ClassPathResource stylesheet = new ClassPathResource("templates/email.css", MailServiceImpl.class);
            //                ClassPathResource stylesheet = new ClassPathResource(MAIL_STYLESHEET, );
            //                message.addInline("email.css", stylesheet, "text/css");                        
        }
    };
    return preparator;
}

From source file:cdr.forms.EmailNotificationHandler.java

@Override
public void notifyError(Deposit deposit, DepositResult result) {

    Form form = deposit.getForm();//from ww w.  ja  v a 2s  .  c o m
    String formId = deposit.getFormId();
    String depositorEmail = deposit.getReceiptEmailAddress();
    List<String> recipients = deposit.getAllDepositNoticeToEmailAddresses();

    // put data into the model
    HashMap<String, Object> model = new HashMap<String, Object>();
    model.put("deposit", deposit);
    model.put("form", form);
    model.put("formId", formId);
    model.put("result", result);
    model.put("depositorEmail", depositorEmail);
    model.put("siteUrl", this.getSiteUrl());
    model.put("siteName", this.getSiteName());
    model.put("receivedDate", new Date(System.currentTimeMillis()));
    StringWriter htmlsw = new StringWriter();
    StringWriter textsw = new StringWriter();

    try {
        depositErrorHtmlTemplate.process(model, htmlsw);
        depositErrorTextTemplate.process(model, textsw);
    } catch (TemplateException e) {
        LOG.error("cannot process email template", e);
        return;
    } catch (IOException e) {
        LOG.error("cannot process email template", e);
        return;
    }

    try {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED);

        if (administratorAddress != null && administratorAddress.trim().length() > 0) {
            message.addTo(this.administratorAddress);
        }

        for (String recipient : recipients) {
            message.addTo(recipient);
        }

        message.setSubject("Deposit Error for " + form.getTitle());
        message.setFrom(this.getFromAddress());
        message.setText(textsw.toString(), htmlsw.toString());
        this.mailSender.send(mimeMessage);
    } catch (MessagingException e) {
        LOG.error("problem sending error notification message", e);
        return;
    }

}

From source file:org.appverse.web.framework.backend.api.services.integration.impl.live.MailIntegrationServiceImpl.java

@SuppressWarnings("unchecked")
@Override// w ww  . j  a  v a 2  s .c o  m
public void sendMail(String from, String[] to, String[] copyTo, String subject, String templateLocation,
        Map model, ArrayList<AttachmentDTO> attachments) throws Exception {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    if (copyTo != null) {
        helper.setCc(copyTo);
    }
    helper.setSubject(subject);
    String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, ENCODING, templateLocation,
            model);
    helper.setText(text, true);
    for (AttachmentDTO attachmentDTO : attachments) {
        helper.addAttachment(attachmentDTO.getAttachmentName(), attachmentDTO.getAttachment());
    }
    try {
        this.mailSender.send(message);
    } catch (MailSendException sendMailException) {
        Exception[] messageExceptions = sendMailException.getMessageExceptions();
        for (Exception messageException : messageExceptions) {
            if (messageException instanceof SendFailedException) {
                SendFailedException sendFailedException = (SendFailedException) messageException;
                if (sendFailedException.getMessage().equals(INVALID_ADDRESSES)) {
                    Address[] invalidAddresses = sendFailedException.getInvalidAddresses();
                    List<String> invalidAddressList = new ArrayList<String>();
                    for (Address invalidAddress : invalidAddresses) {
                        String invalidAddressString = invalidAddress.toString();
                        invalidAddressList.add(invalidAddressString);
                    }
                    List<String> validToAdressesList = new ArrayList<String>();
                    if (to != null && to.length > 0) {
                        for (String address : to) {
                            if (!invalidAddressList.contains(address)) {
                                validToAdressesList.add(address);
                            }
                        }
                    }

                    List<String> validCopyToAdressesList = new ArrayList<String>();
                    if (copyTo != null && copyTo.length > 0) {
                        for (String address : copyTo) {
                            if (!invalidAddressList.contains(address)) {
                                validCopyToAdressesList.add(address);
                            }
                        }
                    }

                    String[] validToAdressesArray = new String[validToAdressesList.size()];
                    validToAdressesList.toArray(validToAdressesArray);
                    helper.setTo(validToAdressesList.toArray(validToAdressesArray));

                    String[] validCopyToAdressesArray = new String[validCopyToAdressesList.size()];
                    validCopyToAdressesList.toArray(validCopyToAdressesArray);
                    helper.setCc(validCopyToAdressesList.toArray(validCopyToAdressesArray));
                    for (String invalidAddress : invalidAddressList) {
                        logger.error("Mail not sended to " + invalidAddress + "due its a invalid address");
                    }
                    this.mailSender.send(message);
                }
            }
        }
    }
}

From source file:uk.ac.gda.dls.client.feedback.FeedbackDialog.java

@Override
protected void createButtonsForButtonBar(Composite parent) {

    GridData data = new GridData(SWT.FILL, SWT.FILL, false, true, 4, 1);
    GridLayout layout = new GridLayout(5, false);
    parent.setLayoutData(data);//from   www .  j a va  2 s  .  com
    parent.setLayout(layout);

    Button attachButton = new Button(parent, SWT.TOGGLE);
    attachButton.setText("Attach File(s)");
    attachButton.setToolTipText("Add files to feedback");

    final Button screenGrabButton = new Button(parent, SWT.CHECK);
    screenGrabButton.setText("Include Screenshot");
    screenGrabButton.setToolTipText("Send screenshot with feedback");

    Label space = new Label(parent, SWT.NONE);
    space.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));

    Button sendButton = new Button(parent, SWT.PUSH);
    sendButton.setText("Send");

    Button cancelButton = new Button(parent, SWT.PUSH);
    cancelButton.setText("Cancel");

    sendButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {

            final String name = nameText.getText();
            final String email = emailText.getText();
            final String subject = subjectText.getText();
            final String description = descriptionText.getText();

            fileList = attachedFileList.getItems();

            Job job = new Job("Send feedback email") {
                @Override
                protected IStatus run(IProgressMonitor monitor) {

                    try {
                        final String recipientsProperty = LocalProperties.get("gda.feedback.recipients",
                                "dag-group@diamond.ac.uk");
                        final String[] recipients = recipientsProperty.split(" ");
                        for (int i = 0; i < recipients.length; i++) {
                            recipients[i] = recipients[i].trim();
                        }

                        final String from = String.format("%s <%s>", name, email);

                        final String beamlineName = LocalProperties.get("gda.beamline.name",
                                "Beamline Unknown");
                        final String mailSubject = String.format("[GDA feedback - %s] %s",
                                beamlineName.toUpperCase(), subject);

                        final String smtpHost = LocalProperties.get("gda.feedback.smtp.host", "localhost");

                        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
                        mailSender.setHost(smtpHost);

                        MimeMessage message = mailSender.createMimeMessage();
                        final MimeMessageHelper helper = new MimeMessageHelper(message,
                                (FeedbackDialog.this.hasFiles && fileList.length > 0)
                                        || FeedbackDialog.this.screenshot);
                        helper.setFrom(from);
                        helper.setTo(recipients);
                        helper.setSubject(mailSubject);
                        helper.setText(description);

                        if (FeedbackDialog.this.screenshot) {
                            PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {

                                @Override
                                public void run() {
                                    String fileName = "/tmp/feedbackScreenshot.png";
                                    try {
                                        captureScreen(fileName);
                                        FileSystemResource file = new FileSystemResource(new File(fileName));
                                        helper.addAttachment(file.getFilename(), file);
                                    } catch (Exception e) {
                                        logger.error("Could not attach screenshot to feedback", e);
                                    }
                                }
                            });
                        }

                        if (FeedbackDialog.this.hasFiles) {
                            for (String fileName : fileList) {
                                FileSystemResource file = new FileSystemResource(new File(fileName));
                                helper.addAttachment(file.getFilename(), file);
                            }
                        }

                        {//required to workaround class loader issue with "no object DCH..." error
                            MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
                            mc.addMailcap(
                                    "text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
                            mc.addMailcap(
                                    "multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
                            CommandMap.setDefaultCommandMap(mc);
                        }
                        mailSender.send(message);
                        return Status.OK_STATUS;
                    } catch (Exception ex) {
                        logger.error("Could not send feedback", ex);
                        return new Status(IStatus.ERROR, Activator.PLUGIN_ID, 1, "Error sending email", ex);
                    }

                }
            };

            job.schedule();

            setReturnCode(OK);
            close();
        }
    });

    cancelButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            setReturnCode(CANCEL);
            close();
        }
    });

    attachButton.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            hasFiles = !hasFiles;
            GridData data = ((GridData) attachments.getLayoutData());
            data.exclude = !hasFiles;
            attachments.setVisible(hasFiles);
            topParent.layout();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });

    screenGrabButton.addSelectionListener(new SelectionListener() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            screenshot = ((Button) e.widget).getSelection();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });
}

From source file:app.service.CaptchaService.java

protected void sendEmail(String email, String authCode)
        throws MessagingException, UnsupportedEncodingException {
    MimeMessage mimeMessage = mMailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8");
    helper.setSubject(" LsPush ");
    helper.setFrom(serverEmail, serverName);
    helper.setTo(email);//from   www  .  j  av  a 2 s . co m

    String authLink = String.format("%s/user/auth?auth_code=%s", serverUrl, authCode);
    final Context ctx = new Context(Locale.CHINA);
    ctx.setVariable("serverUrl", serverUrl);
    ctx.setVariable("serverName", serverName);
    ctx.setVariable("email", email);
    ctx.setVariable("authCode", authCode);
    ctx.setVariable("authLink", authLink);

    String html = mTemplateEngine.process("lspush_captcha_email", ctx);

    helper.setText(html, true);
    mMailSender.send(mimeMessage);
}

From source file:mx.edu.um.mateo.general.web.UsuarioController.java

@Transactional
@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response, @Valid Usuario usuario,
        BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam Boolean enviaCorreo) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }//w  w  w  .j  a  v a2s. c o  m
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        List<Rol> roles = obtieneRoles();
        modelo.addAttribute("roles", roles);
        return "admin/usuario/nuevo";
    }

    String password = null;
    try {
        log.debug("Evaluando roles {}", request.getParameterValues("roles"));
        String[] roles = request.getParameterValues("roles");
        if (roles == null || roles.length == 0) {
            log.debug("Asignando ROLE_USER por defecto");
            roles = new String[] { "ROLE_USER" };
        }
        Long almacenId = (Long) request.getSession().getAttribute("almacenId");
        password = KeyGenerators.string().generateKey();
        usuario.setPassword(password);
        usuario = usuarioDao.crea(usuario, almacenId, roles);

        if (enviaCorreo) {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(usuario.getCorreo());
            helper.setSubject(messageSource.getMessage("envia.correo.password.titulo.message", new String[] {},
                    request.getLocale()));
            helper.setText(messageSource.getMessage("envia.correo.password.contenido.message",
                    new String[] { usuario.getNombre(), usuario.getUsername(), password }, request.getLocale()),
                    true);
            mailSender.send(message);
        }

    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear al usuario", e);
        errors.rejectValue("username", "campo.duplicado.message", new String[] { "username" }, null);
        List<Rol> roles = obtieneRoles();
        modelo.addAttribute("roles", roles);
        return "admin/usuario/nuevo";
    } catch (MessagingException e) {
        log.error("No se pudo enviar la contrasena por correo", e);

        redirectAttributes.addFlashAttribute("message", "usuario.creado.sin.correo.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { usuario.getUsername(), password });

        return "redirect:/admin/usuario/ver/" + usuario.getId();
    }

    redirectAttributes.addFlashAttribute("message", "usuario.creado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { usuario.getUsername() });

    return "redirect:/admin/usuario/ver/" + usuario.getId();
}