List of usage examples for org.springframework.mail.javamail MimeMessageHelper MimeMessageHelper
public MimeMessageHelper(MimeMessage mimeMessage, int multipartMode) throws MessagingException
From source file:info.jtrac.mail.MailSender.java
public void sendUserPassword(User user, String clearText) { if (sender == null) { logger.debug("mail sender is null, not sending new user / password change notification"); return;/*from w ww . j a v a 2s. c om*/ } logger.debug("attempting to send mail for user password"); String localeString = user.getLocale(); Locale locale = null; if (localeString == null) { locale = defaultLocale; } else { locale = StringUtils.parseLocaleString(localeString); } MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8"); try { helper.setTo(user.getEmail()); helper.setSubject(prefix + " " + fmt("loginMailSubject", locale)); StringBuffer sb = new StringBuffer(); sb.append("<p>" + fmt("loginMailGreeting", locale) + " " + user.getName() + ",</p>"); sb.append("<p>" + fmt("loginMailLine1", locale) + "</p>"); sb.append("<table class='jtrac'>"); sb.append("<tr><th style='background: #CCCCCC'>" + fmt("loginName", locale) + "</th><td style='border: 1px solid black'>" + user.getLoginName() + "</td></tr>"); sb.append("<tr><th style='background: #CCCCCC'>" + fmt("password", locale) + "</th><td style='border: 1px solid black'>" + clearText + "</td></tr>"); sb.append("</table>"); sb.append("<p>" + fmt("loginMailLine2", locale) + "</p>"); sb.append("<p><a href='" + url + "'>" + url + "</a></p>"); helper.setText(addHeaderAndFooter(sb), true); helper.setSentDate(new Date()); // helper.setCc(from); helper.setFrom(from); sendInNewThread(message); } catch (Exception e) { logger.error("failed to prepare e-mail", e); } }
From source file:eionet.meta.service.EmailServiceImpl.java
/** * {@inheritDoc}/* w w w. ja v a 2s . co m*/ */ @Override public void notifySiteCodeReservation(String userName, int startIdentifier, int reserveAmount) throws ServiceException { try { SiteCodeAddedNotification notification = new SiteCodeAddedNotification(); notification.setCreatedTime(new Date().toString()); notification.setUsername(userName); notification.setNewCodesStartIdentifier(Integer.toString(startIdentifier)); notification.setNofAddedCodes(Integer.toString(reserveAmount)); notification.setNewCodesEndIdentifier(Integer.toString(startIdentifier + reserveAmount - 1)); notification.setTotalNumberOfAvailableCodes(Integer.toString(siteCodeDao.getFeeSiteCodeAmount())); final String[] to; // if test e-mail is provided, then do not send notification to actual receivers if (!StringUtils.isEmpty(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO))) { notification.setTest(true); notification.setTo(Props.getRequiredProperty(PropsIF.SITE_CODE_RESERVE_NOTIFICATION_TO)); to = StringUtils.split(Props.getProperty(PropsIF.SITE_CODE_TEST_NOTIFICATION_TO), ","); } else { to = StringUtils.split(Props.getRequiredProperty(PropsIF.SITE_CODE_RESERVE_NOTIFICATION_TO), ","); } Map<String, Object> map = new HashMap<String, Object>(); map.put("data", notification); final String text = processTemplate("site_code_reservation.ftl", map); MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false); message.setText(text, false); message.setFrom( new InternetAddress(Props.getRequiredProperty(PropsIF.SITE_CODE_NOTIFICATION_FROM))); message.setSubject("New site codes added"); message.setTo(to); } }; mailSender.send(mimeMessagePreparator); } catch (Exception e) { throw new ServiceException("Failed to send new site codes reservation notification: " + e.toString(), e); } }
From source file:cdr.forms.EmailNotificationHandler.java
private void sendReceipt(HashMap<String, Object> model, Form form, String recipient) { if (recipient == null || recipient.trim().length() == 0) return;/*from w w w . j a v a 2 s .co m*/ StringWriter htmlsw = new StringWriter(); StringWriter textsw = new StringWriter(); try { depositReceiptHtmlTemplate.process(model, htmlsw); depositReceiptTextTemplate.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); message.addTo(recipient); message.setSubject("Deposit Receipt for " + form.getTitle()); message.setFrom(this.getFromAddress()); message.setText(textsw.toString(), htmlsw.toString()); this.mailSender.send(mimeMessage); } catch (MessagingException e) { LOG.error("problem sending deposit message", e); return; } }
From source file:edu.unc.lib.dl.services.MailNotifier.java
/** * @param e// ww w . j av a2 s. c o m * @param user */ public void sendIngestFailureNotice(Throwable ex, IngestProperties props) { String html = null, text = null; MimeMessage mimeMessage = null; boolean logEmail = true; try { // create templates Template htmlTemplate = this.freemarkerConfiguration.getTemplate("IngestFailHtml.ftl", Locale.getDefault(), "utf-8"); Template textTemplate = this.freemarkerConfiguration.getTemplate("IngestFailText.ftl", Locale.getDefault(), "utf-8"); if (log.isDebugEnabled() && this.mailSender instanceof JavaMailSenderImpl) { ((JavaMailSenderImpl) this.mailSender).getSession().setDebug(true); } // create mail message mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED); // put data into the model HashMap<String, Object> model = new HashMap<String, Object>(); model.put("irBaseUrl", this.irBaseUrl); /* List<ContainerPlacement> tops = new ArrayList<ContainerPlacement>(); tops.addAll(props.getContainerPlacements().values()); model.put("tops", tops);*/ if (ex != null && ex.getMessage() != null) { model.put("message", ex.getMessage()); } else if (ex != null) { model.put("message", ex.toString()); } else { model.put("message", "No exception or error message available."); } // specific exception processing if (ex instanceof FilesDoNotMatchManifestException) { model.put("FilesDoNotMatchManifestException", ex); } else if (ex instanceof InvalidMETSException) { model.put("InvalidMETSException", ex); InvalidMETSException ime = (InvalidMETSException) ex; if (ime.getSvrl() != null) { Document jdomsvrl = ((InvalidMETSException) ex).getSvrl(); DOMOutputter domout = new DOMOutputter(); try { org.w3c.dom.Document svrl = domout.output(jdomsvrl); model.put("svrl", NodeModel.wrap(svrl)); // also dump SVRL to attachment message.addAttachment("schematron-output.xml", new JDOMStreamSource(jdomsvrl)); } catch (JDOMException e) { throw new Error(e); } } } else if (ex instanceof METSParseException) { log.debug("putting MPE in the model"); model.put("METSParseException", ex); } else { log.debug("IngestException without special email treatment", ex); } // attach error xml if available if (ex instanceof IngestException) { IngestException ie = (IngestException) ex; if (ie.getErrorXML() != null) { message.addAttachment("error.xml", new JDOMStreamSource(ie.getErrorXML())); } } model.put("user", props.getSubmitter()); model.put("irBaseUrl", this.irBaseUrl); StringWriter sw = new StringWriter(); htmlTemplate.process(model, sw); html = sw.toString(); sw = new StringWriter(); textTemplate.process(model, sw); text = sw.toString(); // Addressing: to initiator if a person, otherwise to all members of // admin group if (props.getEmailRecipients() != null) { for (String r : props.getEmailRecipients()) { message.addTo(r); } } message.addTo(this.getAdministratorAddress(), "CDR Administrator"); message.setSubject("CDR ingest failed"); message.setFrom(this.getRepositoryFromAddress()); message.setText(text, html); // attach Events XML // if (aip != null) { // /message.addAttachment("events.xml", new JDOMStreamSource(aip.getEventLogger().getAllEvents())); // } this.mailSender.send(mimeMessage); logEmail = false; } catch (MessagingException e) { log.error("Unable to send ingest fail email.", e); } catch (MailSendException e) { log.error("Unable to send ingest fail email.", e); } catch (UnsupportedEncodingException e) { log.error("Unable to send ingest fail email.", e); } catch (IOException e1) { throw new Error("Unable to load email template for Ingest Failure", e1); } catch (TemplateException e) { throw new Error("There was a problem loading FreeMarker templates for email notification", 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: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 . ja v a 2 s .co 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:cdr.forms.EmailNotificationHandler.java
private void sendNotice(HashMap<String, Object> model, Form form, List<String> recipients) { if (recipients == null || recipients.isEmpty()) return;//from w w w. j av a2 s . c om StringWriter htmlsw = new StringWriter(); StringWriter textsw = new StringWriter(); try { depositNoticeHtmlTemplate.process(model, htmlsw); depositNoticeTextTemplate.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); for (String recipient : recipients) { message.addTo(recipient); } message.setSubject("Deposit to " + form.getTitle() + " by " + form.getCurrentUser()); message.setFrom(this.getFromAddress()); message.setText(textsw.toString(), htmlsw.toString()); this.mailSender.send(mimeMessage); } catch (MessagingException e) { LOG.error("problem sending deposit message", e); return; } }
From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java
public void handleResult(final MultiFilesResult result) throws MessagingException, IOException { final Serializable responseBody = result.getMeta().get(EMAIL_BODY_META_NAME); final String responseText = responseBody instanceof File ? FileUtils.readFileToString((File) responseBody) : responseBody.toString();//from w w w . ja v a 2 s. c o m final MimeMessage mimeMessage = mailSender.createMimeMessage(); final MimeMessageHelper mmh = new MimeMessageHelper(mimeMessage, true); mmh.setFrom((String) result.getMeta().get(EMAIL_ADDRESSEE_META_NAME)); mmh.setTo((String) result.getMeta().get(EMAIL_REPLY_TO_META_NAME)); mmh.setCc((String[]) result.getMeta().get(EMAIL_REPLY_CC_META_NAME)); mmh.setSubject("RE: " + result.getMeta().get(EMAIL_SUBJECT_META_NAME)); if (result.isSuccess()) { mmh.setText(responseText); for (final File resultFile : result.getPayload()) { mmh.addAttachment(resultFile.getName(), resultFile); } } else { mmh.setText(FileUtils.readFileToString(result.getPayload()[0])); } final Message<MimeMailMessage> message = new GenericMessage<MimeMailMessage>(new MimeMailMessage(mmh)); outboundEmailChannel.send(message); }
From source file:it.jugpadova.blo.ParticipantBo.java
/** * General participant mail sender/*from w ww. ja v a 2 s . c o m*/ * * @param participant * @param baseUrl * @param subject * @param oneWayCode * @param template */ private void sendEmail(final Participant participant, final String baseUrl, final String subject, final String template, final Resource attachment, final String attachmentName) { MimeMessagePreparator preparator = new MimeMessagePreparator() { @SuppressWarnings(value = "unchecked") public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true); message.setTo(participant.getEmail()); message.setFrom(conf.getConfirmationSenderEmailAddress()); message.setSubject(subject); Map model = new HashMap(); model.put("participant", participant); model.put("baseUrl", baseUrl); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model); message.setText(text, true); if (attachment != null) { message.addAttachment(attachmentName, attachment); } } }; this.mailSender.send(preparator); }
From source file:gov.nih.nci.cabig.caaers.esb.client.MessageNotificationService.java
public void sendMail(String[] to, String subject, String content, String attachment) throws Exception { MimeMessage message = caaersJavaMailSender.createMimeMessage(); message.setSubject(subject);//from www .j a v a 2 s.c o m message.setFrom(new InternetAddress(configuration.get(Configuration.SYSTEM_FROM_EMAIL))); // use the true flag to indicate you need a multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setText(content); if (attachment != null) { File f = new File(attachment); FileSystemResource file = new FileSystemResource(f); helper.addAttachment(file.getFilename(), file); } caaersJavaMailSender.send(message); }
From source file:mx.edu.um.mateo.rh.web.DiaFeriadoController.java
private void enviaCorreo(String tipo, List<DiaFeriado> diaFeriados, HttpServletRequest request) throws JRException, MessagingException { log.debug("Enviando correo {}", tipo); byte[] archivo = null; String tipoContenido = null;/*from w w w. ja v a2 s . c om*/ switch (tipo) { case "PDF": archivo = generaPdf(diaFeriados); tipoContenido = "application/pdf"; break; case "CSV": archivo = generaCsv(diaFeriados); tipoContenido = "text/csv"; break; case "XLS": archivo = generaXls(diaFeriados); tipoContenido = "application/vnd.ms-excel"; } MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(ambiente.obtieneUsuario().getUsername()); String titulo = messageSource.getMessage("diaFeriado.lista.label", null, request.getLocale()); helper.setSubject(messageSource.getMessage("envia.correo.titulo.message", new String[] { titulo }, request.getLocale())); helper.setText(messageSource.getMessage("envia.correo.contenido.message", new String[] { titulo }, request.getLocale()), true); helper.addAttachment(titulo + "." + tipo, new ByteArrayDataSource(archivo, tipoContenido)); mailSender.send(message); }