List of usage examples for org.springframework.mail.javamail MimeMessageHelper setSubject
public void setSubject(String subject) throws MessagingException
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;/*from w w w . jav 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.akaza.openclinica.controller.SystemController.java
public String sendEmail(JavaMailSenderImpl mailSender, String emailSubject, String message) throws OpenClinicaSystemException { logger.info("Sending email..."); try {/*from w ww . ja va 2s . com*/ 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//from w w w . ja v a 2 s . c o 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 ww . j a v a 2 s.c om * @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 .j av a 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; }
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 .c o 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; }
From source file:org.apache.syncope.core.notification.NotificationJob.java
public TaskExec executeSingle(final NotificationTask task) { init();/*from w ww . j a va 2s . com*/ TaskExec execution = new TaskExec(); 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(ExceptionUtil.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().getId(), true); } return execution; }
From source file:org.apache.syncope.core.provisioning.java.job.notification.NotificationJobDelegate.java
@Transactional public TaskExec executeSingle(final NotificationTask task) { TaskExec execution = entityFactory.newEntity(TaskExec.class); execution.setTask(task);//from w ww.j a v a 2s.c o m 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()); } notificationManager.createTasks(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)); } notificationManager.createTasks(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; }
From source file:org.apereo.portal.portlets.account.EmailPasswordResetNotificationImpl.java
@Override public void sendNotification(URL resetUrl, ILocalAccountPerson account, Locale locale) { log.debug("Sending password reset instructions to user with url {}", resetUrl.toString()); try {//from w w w . j a v a 2s . c o m MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); String email = (String) account.getAttributeValue(ILocalAccountPerson.ATTR_MAIL); String subject = messageSource.getMessage(subjectMessageKey, new Object[] {}, locale); String body = formatBody(resetUrl, account, locale); helper.addTo(email); helper.setText(body, true); helper.setSubject(subject); helper.setFrom(portalEmailAddress, messageSource.getMessage("portal.name", new Object[] {}, locale)); log.debug("Sending message to {} from {} subject {}", email, Arrays.toString(message.getFrom()), message.getSubject()); this.mailSender.send(helper.getMimeMessage()); } catch (Exception e) { log.error("Unable to send password reset email", e); } }
From source file:org.beangle.notification.notifiers.mail.AbstractMailNotifier.java
public void deliver(T mailMsg) throws NotificationException { MimeMessage mimeMsg = mailSender.createMimeMessage(); try {/*from w w w . j av a2 s . c o m*/ if (null == mailMsg.getSendAt()) { mimeMsg.setSentDate(new Date()); } else { mimeMsg.setSentDate(mailMsg.getSendAt()); } MimeMessageHelper messageHelper = null; String encoding = StringUtils.substringAfter(mailMsg.getContentType(), "charset="); if (StringUtils.isEmpty(encoding)) { messageHelper = new MimeMessageHelper(mimeMsg); } else { messageHelper = new MimeMessageHelper(mimeMsg, encoding); } messageHelper.setText(buildText(mailMsg), StringUtils.contains(mailMsg.getContentType(), "html")); String subject = buildSubject(mailMsg); messageHelper.setSubject(subject); int recipients = addRecipient(mimeMsg, mailMsg); beforeSend(mailMsg, mimeMsg); if (recipients > 0) { mailSender.send(mimeMsg); if (logger.isDebugEnabled()) { logger.debug("mail sended from {} to {} with subject {}", new Object[] { from, mailMsg.getRecipients(), subject }); } } else { logger.warn("{} without any recipients ,sending aborted!", subject); } } catch (AddressException ex) { throw new NotificationException("Exception while sending message.", ex); } catch (MessagingException ex) { throw new NotificationException("Exception while sending message.", ex); } afterSend(mailMsg, mimeMsg); }