List of usage examples for org.springframework.mail.javamail MimeMessageHelper setFrom
public void setFrom(String from) throws MessagingException
From source file:gr.abiss.calipso.mail.MailSender.java
public void sendUserPassword(User user, String clearText) { if (sender == null) { logger.warn("mail sender is null, not sending new user / password change notification"); return;//w ww .j a v a 2 s.com } if (logger.isDebugEnabled()) { logger.debug("attempting to send mail for user password"); } Locale locale = getUserLocale(user); try { MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); helper.setTo(user.getEmail()); helper.setSubject(prefix + " " + fmt("loginMailSubject", locale)); StringBuffer sb = new StringBuffer(); String greeting = fmt("loginMailGreeting", locale); if (org.apache.commons.lang.StringUtils.isNotBlank(greeting)) { sb.append("<p>" + fmt("loginMailGreeting", locale) + " " + user.getName() + ",</p>"); } sb.append("<p>" + fmt("loginMailLine1", locale) + "</p>"); sb.append("<table class='calipsoService'>"); 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>"); sb.append("<p>" + fmt("loginMailLine3", locale) + "</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:au.org.theark.core.service.ArkCommonServiceImpl.java
public void sendEmail(final SimpleMailMessage simpleMailMessage) throws MailSendException, VelocityException { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(simpleMailMessage.getTo()); // The "from" field is required if (simpleMailMessage.getFrom() == null) { simpleMailMessage.setFrom(Constants.ARK_ADMIN_EMAIL); }// ww w . ja va2 s . c o m message.setFrom(simpleMailMessage.getFrom()); message.setSubject(simpleMailMessage.getSubject()); // Map all the fields for the email template Map<String, Object> model = new HashMap<String, Object>(); // Add the host name into the footer of the email String host = InetAddress.getLocalHost().getHostName(); // Message title model.put("title", "Message from The ARK"); // Message header model.put("header", "Message from The ARK"); // Message subject model.put("subject", simpleMailMessage.getSubject()); // Message text model.put("text", simpleMailMessage.getText()); // Hostname in message footer model.put("host", host); // TODO: Add inline image(s)?? // Add inline image header // FileSystemResource res = new FileSystemResource(new // File("c:/Sample.jpg")); // message.addInline("bgHeaderImg", res); // Set up the email text String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "au/org/theark/core/velocity/resetPasswordEmail.vm", model); message.setText(text, true); } }; // send out the email javaMailSender.send(preparator); }
From source file:edu.unc.lib.dl.services.MailNotifier.java
/** * @param e/*from w w w . j a va2s .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: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;/* www. j av a 2 s . c o 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:ome.services.mail.MailUtil.java
/** * Main method which takes typical email fields as arguments, to prepare and * populate the given new MimeMessage instance and send. * * @param from/*from www .ja v a 2 s. co m*/ * email address message is sent from * @param to * email address message is sent to * @param topic * topic of the message * @param body * body of the message * @param html * flag determines the content type to apply. * @param ccrecipients * list of email addresses message is sent as copy to * @param bccrecipients * list of email addresses message is sent as blind copy to */ public void sendEmail(final String from, final String to, final String topic, final String body, final boolean html, final List<String> ccrecipients, final List<String> bccrecipients) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setText(body, html); message.setFrom(from); message.setSubject(topic); message.setTo(to); if (ccrecipients != null && !ccrecipients.isEmpty()) { message.setCc(ccrecipients.toArray(new String[ccrecipients.size()])); } if (bccrecipients != null && !bccrecipients.isEmpty()) { message.setCc(bccrecipients.toArray(new String[bccrecipients.size()])); } } }; this.mailSender.send(preparator); }
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;//w w w .j a v a 2 s .com 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.akaza.openclinica.controller.SystemController.java
public String sendEmail(JavaMailSenderImpl mailSender, String emailSubject, String message) throws OpenClinicaSystemException { logger.info("Sending email..."); try {//w w w .jav a 2s. co m MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage); helper.setFrom(EmailEngine.getAdminEmail()); helper.setTo("oc123@openclinica.com"); helper.setSubject(emailSubject); helper.setText(message); mailSender.send(mimeMessage); return "ACTIVE"; } catch (MailException me) { return "INACTIVE"; } catch (MessagingException me) { return "INACTIVE"; } }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
public void testEncodedFromToAddresses() throws Exception { // RFC1342/* w ww .j a va 2 s. co m*/ String addressString = "ars.kov@gmail.com"; String personalString = "?? "; InternetAddress address = new InternetAddress(addressString, personalString, "UTF-8"); // Following method returns the address with quoted personal aka <["?? "] <ars.kov@gmail.com>> // NOTE! This should be coincided with RFC822MetadataExtracter. Would 'addresses' be quoted or not? // String decodedAddress = address.toUnicodeString(); // So, just using decode, for now String decodedAddress = MimeUtility.decodeText(address.toString()); // InternetAddress.toString(new Address[] {address}) - is used in the RFC822MetadataExtracter // So, compare with that assertFalse("Non ASCII characters in the address should be encoded", decodedAddress.equals(InternetAddress.toString(new Address[] { address }))); MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties())); MimeMessageHelper messageHelper = new MimeMessageHelper(message, false, "UTF-8"); messageHelper.setText("This is a sample message for ALF-5647"); messageHelper.setSubject("This is a sample message for ALF-5647"); messageHelper.setFrom(address); messageHelper.addTo(address); messageHelper.addCc(address); // Creating the message node in the repository String name = AlfrescoImapConst.MESSAGE_PREFIX + GUID.generate(); FileInfo messageFile = fileFolderService.create(testImapFolderNodeRef, name, ContentModel.TYPE_CONTENT); // Writing a content. new IncomingImapMessage(messageFile, serviceRegistry, message); // Getting the transformed properties from the repository // cm:originator, cm:addressee, cm:addressees, imap:messageFrom, imap:messageTo, imap:messageCc Map<QName, Serializable> properties = nodeService.getProperties(messageFile.getNodeRef()); String cmOriginator = (String) properties.get(ContentModel.PROP_ORIGINATOR); String cmAddressee = (String) properties.get(ContentModel.PROP_ADDRESSEE); @SuppressWarnings("unchecked") List<String> cmAddressees = (List<String>) properties.get(ContentModel.PROP_ADDRESSEES); String imapMessageFrom = (String) properties.get(ImapModel.PROP_MESSAGE_FROM); String imapMessageTo = (String) properties.get(ImapModel.PROP_MESSAGE_TO); String imapMessageCc = (String) properties.get(ImapModel.PROP_MESSAGE_CC); assertNotNull(cmOriginator); assertEquals(decodedAddress, cmOriginator); assertNotNull(cmAddressee); assertEquals(decodedAddress, cmAddressee); assertNotNull(cmAddressees); assertEquals(1, cmAddressees.size()); assertEquals(decodedAddress, cmAddressees.get(0)); assertNotNull(imapMessageFrom); assertEquals(decodedAddress, imapMessageFrom); assertNotNull(imapMessageTo); assertEquals(decodedAddress, imapMessageTo); assertNotNull(imapMessageCc); assertEquals(decodedAddress, imapMessageCc); }
From source file:org.alfresco.web.bean.TemplateMailHelperBean.java
/** * Send an email notification to the specified User authority * //from w w w . j ava 2 s.c o m * @param person Person node representing the user * @param node Node they are invited too * @param from From text message * @param roleText The role display label for the user invite notification */ public void notifyUser(NodeRef person, NodeRef node, final String from, String roleText) { final String to = (String) this.getNodeService().getProperty(person, ContentModel.PROP_EMAIL); if (to != null && to.length() != 0) { String body = this.body; if (this.usingTemplate != null) { FacesContext fc = FacesContext.getCurrentInstance(); // use template service to format the email NodeRef templateRef = new NodeRef(Repository.getStoreRef(), this.usingTemplate); ServiceRegistry services = Repository.getServiceRegistry(fc); Map<String, Object> model = DefaultModelHelper.buildDefaultModel(services, Application.getCurrentUser(fc), templateRef); model.put("role", roleText); model.put("space", node); // object to allow client urls to be generated in emails model.put("url", new BaseTemplateContentServlet.URLHelper(fc)); model.put("msg", new I18NMessageMethod()); model.put("document", node); if (nodeService.getType(node).equals(ContentModel.TYPE_CONTENT)) { NodeRef parentNodeRef = nodeService.getParentAssocs(node).get(0).getParentRef(); if (parentNodeRef == null) { throw new IllegalArgumentException("Parent folder doesn't exists for node: " + node); } model.put("space", parentNodeRef); } model.put("shareUrl", UrlUtil.getShareUrl(services.getSysAdminParams())); body = services.getTemplateService().processTemplate("freemarker", templateRef.toString(), model); } this.finalBody = body; MimeMessagePreparator mailPreparer = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(to); message.setSubject(subject); message.setText(finalBody, MailActionExecuter.isHTML(finalBody)); message.setFrom(from); } }; if (logger.isDebugEnabled()) logger.debug("Sending notification email to: " + to + "\n...with subject:\n" + subject + "\n...with body:\n" + body); try { // Send the message this.getMailSender().send(mailPreparer); } catch (Throwable e) { // don't stop the action but let admins know email is not getting sent logger.error("Failed to send email to " + to, e); } } }
From source file:org.apache.syncope.core.logic.notification.NotificationJob.java
public TaskExec executeSingle(final NotificationTask task) { init();/*from w w w . ja va 2 s. com*/ 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; }