List of usage examples for org.springframework.mail.javamail MimeMessageHelper MimeMessageHelper
public MimeMessageHelper(MimeMessage mimeMessage, int multipartMode) throws MessagingException
From source file:mx.edu.um.mateo.general.web.BaseController.java
protected void enviaCorreo(String tipo, List<?> lista, HttpServletRequest request, String nombre, String tipoReporte, Long id) throws ReporteException { try {/* ww w . j ava 2 s . c o m*/ log.debug("Enviando correo {}", tipo); byte[] archivo = null; String tipoContenido = null; switch (tipo) { case "PDF": archivo = generaPdf(lista, nombre, tipoReporte, id); tipoContenido = "application/pdf"; break; case "CSV": archivo = generaCsv(lista, nombre, tipoReporte, id); tipoContenido = "text/csv"; break; case "XLS": archivo = generaXls(lista, nombre, tipoReporte, id); tipoContenido = "application/vnd.ms-excel"; } MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(ambiente.obtieneUsuario().getCorreo()); String titulo = messageSource.getMessage(nombre + ".reporte.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); } catch (JRException | MessagingException e) { throw new ReporteException("No se pudo generar el reporte", e); } }
From source file:mx.edu.um.mateo.rh.web.EstudiosEmpleadoController.java
private void enviaCorreo(String tipo, List<EstudiosEmpleado> estudiosEmpleados, HttpServletRequest request) throws JRException, MessagingException { log.debug("Enviando correo {}", tipo); byte[] archivo = null; String tipoContenido = null;//from www . ja v a 2 s . c om switch (tipo) { case "PDF": archivo = generaPdf(estudiosEmpleados); tipoContenido = "application/pdf"; break; case "CSV": archivo = generaCsv(estudiosEmpleados); tipoContenido = "text/csv"; break; case "XLS": archivo = generaXls(estudiosEmpleados); tipoContenido = "application/vnd.ms-excel"; } MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(ambiente.obtieneUsuario().getUsername()); String titulo = messageSource.getMessage("estudiosEmpleado.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); }
From source file:de.thm.arsnova.services.UserService.java
private void sendEmail(DbUser dbUser, String subject, String body) { MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, "UTF-8"); try {// w w w .ja v a 2 s.co m helper.setFrom(mailSenderName + "<" + mailSenderAddress + ">"); helper.setTo(dbUser.getUsername()); helper.setSubject(subject); helper.setText(body); LOGGER.info("Sending mail \"{}\" from \"{}\" to \"{}\"", new Object[] { subject, msg.getFrom(), dbUser.getUsername() }); mailSender.send(msg); } catch (MessagingException e) { LOGGER.warn("Mail \"{}\" could not be sent: {}", subject, e); } catch (MailException e) { LOGGER.warn("Mail \"{}\" could not be sent: {}", subject, e); } }
From source file:com.campodejazayeri.wedding.AdminController.java
private void sendEmail(String to, String subject, String body) throws Exception { MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, "UTF-8"); helper.setFrom("Darius and Monica <campodejazayeri@gmail.com>"); helper.setTo(to);//from w w w . j a v a2s .c o m helper.setSubject(subject); helper.setText(body); mailSender.send(msg); }
From source file:de.thm.arsnova.service.UserServiceImpl.java
private void sendEmail(UserProfile userProfile, String subject, String body) { MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, "UTF-8"); try {// ww w .j ava2s. c om helper.setFrom(mailSenderName + "<" + mailSenderAddress + ">"); helper.setTo(userProfile.getLoginId()); helper.setSubject(subject); helper.setText(body); logger.info("Sending mail \"{}\" from \"{}\" to \"{}\"", subject, msg.getFrom(), userProfile.getLoginId()); mailSender.send(msg); } catch (MailException | MessagingException e) { logger.warn("Mail \"{}\" could not be sent.", subject, e); } }
From source file:com.cubusmail.mail.MessageHandler.java
/** * @throws MessagingException// www . j av a 2 s. c om * @throws IOException */ private void buildBodyContent() throws MessagingException, IOException { boolean hasAttachments = (this.composeAttachments != null && this.composeAttachments.size() > 0); boolean multipart = hasAttachments || isHtmlMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(this.message, multipart); if (isHtmlMessage()) { String plainText = MessageTextUtil.convertHtml2PlainText(this.messageTextHtml); messageHelper.setText(plainText, this.messageTextHtml); } else { messageHelper.setText(this.messageTextPlain, false); } if (hasAttachments) { for (DataSource attachment : this.composeAttachments) { messageHelper.addAttachment(attachment.getName(), attachment); } } if (!isRead()) { this.message.setFlag(Flags.Flag.SEEN, true); } }
From source file:nl.strohalm.cyclos.utils.MailHandler.java
private void doSend(final String subject, final InternetAddress replyTo, final InternetAddress to, final String body, final boolean isHTML, final boolean throwException) { if (to == null || StringUtils.isEmpty(to.getAddress())) { return;/*from ww w . j a va2 s .co m*/ } final LocalSettings localSettings = settingsService.getLocalSettings(); final MailSettings mailSettings = settingsService.getMailSettings(); final JavaMailSender mailSender = mailSettings.getMailSender(); final MimeMessage message = mailSender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(message, localSettings.getCharset()); try { helper.setFrom(getSystemAddress()); if (replyTo != null) { helper.setReplyTo(replyTo); } helper.setTo(to); helper.setSubject(subject); helper.setText(body, isHTML); mailSender.send(message); } catch (final MessagingException e) { if (throwException) { throw new MailSendingException(subject, e); } // Store the current Exception CurrentTransactionData.setMailError(new MailSendingException(subject, e)); } catch (final MailException e) { if (throwException) { throw new MailSendingException(subject, e); } CurrentTransactionData.setMailError(new MailSendingException(subject, e)); } }
From source file:org.akaza.openclinica.control.core.SecureController.java
License:asdf
public Boolean sendEmail(String to, String from, String subject, String body, Boolean htmlEmail, String successMessage, String failMessage, Boolean sendMessage) throws Exception { Boolean messageSent = true;/*ww w.ja v a 2 s. c o m*/ try { JavaMailSenderImpl mailSender = (JavaMailSenderImpl) SpringServletAccess.getApplicationContext(context) .getBean("mailSender"); // @pgawade 09-Feb-2012 #issue 13201 - setting the "mail.smtp.localhost" property to localhost when java API // is not able to // retrieve the host name Properties javaMailProperties = mailSender.getJavaMailProperties(); if (null != javaMailProperties) { if (javaMailProperties.get("mail.smtp.localhost") == null || ((String) javaMailProperties.get("mail.smtp.localhost")).equalsIgnoreCase("")) { javaMailProperties.put("mail.smtp.localhost", "localhost"); } } MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, htmlEmail); helper.setFrom(from); helper.setTo(processMultipleImailAddresses(to.trim())); helper.setSubject(subject); helper.setText(body, true); mailSender.send(mimeMessage); if (successMessage != null && sendMessage) { addPageMessage(successMessage); } logger.debug("Email sent successfully on {}", new Date()); } catch (MailException me) { me.printStackTrace(); if (failMessage != null && sendMessage) { addPageMessage(failMessage); } logger.debug("Email could not be sent on {} due to: {}", new Date(), me.toString()); messageSent = false; } return messageSent; }
From source file:org.apache.syncope.core.logic.notification.NotificationJob.java
public TaskExec executeSingle(final NotificationTask task) { init();/*from w w w . j a v a 2 s .c om*/ TaskExec execution = entityFactory.newEntity(TaskExec.class); execution.setTask(task); execution.setStartDate(new Date()); boolean retryPossible = true; if (StringUtils.isBlank(task.getSubject()) || task.getRecipients().isEmpty() || StringUtils.isBlank(task.getHtmlBody()) || StringUtils.isBlank(task.getTextBody())) { String message = "Could not fetch all required information for sending e-mails:\n" + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject() + "\n" + task.getHtmlBody() + "\n" + task.getTextBody(); LOG.error(message); execution.setStatus(Status.NOT_SENT.name()); retryPossible = false; if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) { execution.setMessage(message); } } else { if (LOG.isDebugEnabled()) { LOG.debug("About to send e-mails:\n" + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject() + "\n" + task.getHtmlBody() + "\n" + task.getTextBody() + "\n"); } for (String to : task.getRecipients()) { try { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setFrom(task.getSender()); helper.setSubject(task.getSubject()); helper.setText(task.getTextBody(), task.getHtmlBody()); mailSender.send(message); execution.setStatus(Status.SENT.name()); StringBuilder report = new StringBuilder(); switch (task.getTraceLevel()) { case ALL: report.append("FROM: ").append(task.getSender()).append('\n').append("TO: ").append(to) .append('\n').append("SUBJECT: ").append(task.getSubject()).append('\n') .append('\n').append(task.getTextBody()).append('\n').append('\n') .append(task.getHtmlBody()).append('\n'); break; case SUMMARY: report.append("E-mail sent to ").append(to).append('\n'); break; case FAILURES: case NONE: default: } if (report.length() > 0) { execution.setMessage(report.toString()); } auditManager.audit(AuditElements.EventCategoryType.TASK, "notification", null, "send", Result.SUCCESS, null, null, task, "Successfully sent notification to " + to); } catch (Exception e) { LOG.error("Could not send e-mail", e); execution.setStatus(Status.NOT_SENT.name()); if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) { execution.setMessage(ExceptionUtils2.getFullStackTrace(e)); } auditManager.audit(AuditElements.EventCategoryType.TASK, "notification", null, "send", Result.FAILURE, null, null, task, "Could not send notification to " + to, e); } execution.setEndDate(new Date()); } } if (hasToBeRegistered(execution)) { execution = notificationManager.storeExec(execution); if (retryPossible && (Status.valueOf(execution.getStatus()) == Status.NOT_SENT)) { handleRetries(execution); } } else { notificationManager.setTaskExecuted(execution.getTask().getKey(), true); } return execution; }
From source file:org.apache.syncope.core.logic.notification.NotificationJobDelegate.java
@Transactional public TaskExec executeSingle(final NotificationTask task) { init();/* w ww .j a v a 2 s . co m*/ TaskExec execution = entityFactory.newEntity(TaskExec.class); execution.setTask(task); execution.setStart(new Date()); boolean retryPossible = true; if (StringUtils.isBlank(task.getSubject()) || task.getRecipients().isEmpty() || StringUtils.isBlank(task.getHtmlBody()) || StringUtils.isBlank(task.getTextBody())) { String message = "Could not fetch all required information for sending e-mails:\n" + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject() + "\n" + task.getHtmlBody() + "\n" + task.getTextBody(); LOG.error(message); execution.setStatus(NotificationJob.Status.NOT_SENT.name()); retryPossible = false; if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) { execution.setMessage(message); } } else { if (LOG.isDebugEnabled()) { LOG.debug("About to send e-mails:\n" + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject() + "\n" + task.getHtmlBody() + "\n" + task.getTextBody() + "\n"); } for (String to : task.getRecipients()) { try { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setFrom(task.getSender()); helper.setSubject(task.getSubject()); helper.setText(task.getTextBody(), task.getHtmlBody()); mailSender.send(message); execution.setStatus(NotificationJob.Status.SENT.name()); StringBuilder report = new StringBuilder(); switch (task.getTraceLevel()) { case ALL: report.append("FROM: ").append(task.getSender()).append('\n').append("TO: ").append(to) .append('\n').append("SUBJECT: ").append(task.getSubject()).append('\n') .append('\n').append(task.getTextBody()).append('\n').append('\n') .append(task.getHtmlBody()).append('\n'); break; case SUMMARY: report.append("E-mail sent to ").append(to).append('\n'); break; case FAILURES: case NONE: default: } if (report.length() > 0) { execution.setMessage(report.toString()); } auditManager.audit(AuditElements.EventCategoryType.TASK, "notification", null, "send", AuditElements.Result.SUCCESS, null, null, task, "Successfully sent notification to " + to); } catch (Exception e) { LOG.error("Could not send e-mail", e); execution.setStatus(NotificationJob.Status.NOT_SENT.name()); if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) { execution.setMessage(ExceptionUtils2.getFullStackTrace(e)); } auditManager.audit(AuditElements.EventCategoryType.TASK, "notification", null, "send", AuditElements.Result.FAILURE, null, null, task, "Could not send notification to " + to, e); } execution.setEnd(new Date()); } } if (hasToBeRegistered(execution)) { execution = notificationManager.storeExec(execution); if (retryPossible && (NotificationJob.Status.valueOf(execution.getStatus()) == NotificationJob.Status.NOT_SENT)) { handleRetries(execution); } } else { notificationManager.setTaskExecuted(execution.getTask().getKey(), true); } return execution; }