List of usage examples for org.springframework.mail SimpleMailMessage getSubject
@Nullable
public String getSubject()
From source file:net.triptech.metahive.service.EmailSenderService.java
/** * Send an email message using the configured Spring sender. On success * record the sent message in the datastore for reporting purposes * * @param email the email/*from ww w . j ava2 s .c o m*/ * @param attachments the attachments * @throws ServiceException the service exception */ public final void send(final SimpleMailMessage email, TreeMap<String, Object> attachments) throws ServiceException { // Check to see whether the required fields are set (to, from, message) if (email.getTo() == null) { throw new ServiceException("Error sending email: Recipient " + "address required"); } if (StringUtils.isBlank(email.getFrom())) { throw new ServiceException("Error sending email: Email requires " + "a from address"); } if (StringUtils.isBlank(email.getText())) { throw new ServiceException("Error sending email: No email " + "message specified"); } if (mailSender == null) { throw new ServiceException("The JavaMail sender has not " + "been configured"); } // Prepare the email message MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = null; boolean htmlMessage = false; if (StringUtils.containsIgnoreCase(email.getText(), "<html")) { htmlMessage = true; try { helper = new MimeMessageHelper(message, true, "UTF-8"); } catch (MessagingException me) { throw new ServiceException("Error preparing email for sending: " + me.getMessage()); } } else { helper = new MimeMessageHelper(message); } try { helper.setTo(email.getTo()); helper.setFrom(email.getFrom()); helper.setSubject(email.getSubject()); if (email.getCc() != null) { helper.setCc(email.getCc()); } if (email.getBcc() != null) { helper.setBcc(email.getBcc()); } if (htmlMessage) { String plainText = email.getText(); try { ConvertHtmlToText htmlToText = new ConvertHtmlToText(); plainText = htmlToText.convert(email.getText()); } catch (Exception e) { logger.error("Error converting HTML to plain text: " + e.getMessage()); } helper.setText(plainText, email.getText()); } else { helper.setText(email.getText()); } if (email.getSentDate() != null) { helper.setSentDate(email.getSentDate()); } else { helper.setSentDate(Calendar.getInstance().getTime()); } } catch (MessagingException me) { throw new ServiceException("Error preparing email for sending: " + me.getMessage()); } // Append any attachments (if an HTML email) if (htmlMessage && attachments != null) { for (String id : attachments.keySet()) { Object reference = attachments.get(id); if (reference instanceof File) { try { FileSystemResource res = new FileSystemResource((File) reference); helper.addInline(id, res); } catch (MessagingException me) { logger.error("Error appending File attachment: " + me.getMessage()); } } if (reference instanceof URL) { try { UrlResource res = new UrlResource((URL) reference); helper.addInline(id, res); } catch (MessagingException me) { logger.error("Error appending URL attachment: " + me.getMessage()); } } } } // Send the email message try { mailSender.send(message); } catch (MailException me) { logger.error("Error sending email: " + me.getMessage()); throw new ServiceException("Error sending email: " + me.getMessage()); } }
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); }/* w w w . jav a 2 s . c om*/ 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:com.springsource.insight.plugin.mail.MessageSendOperationCollectionAspectTest.java
private void testSendMessage(int port) { JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost(NetworkAddressUtil.LOOPBACK_ADDRESS); sender.setProtocol(JavaMailSenderImpl.DEFAULT_PROTOCOL); sender.setPort(port);//from w w w . j av a 2 s. co m SimpleMailMessage message = new SimpleMailMessage(); message.setFrom("from@com.springsource.insight.plugin.mail"); message.setTo("to@com.springsource.insight.plugin.mail"); message.setCc("cc@com.springsource.insight.plugin.mail"); message.setBcc("bcc@com.springsource.insight.plugin.mail"); Date now = new Date(System.currentTimeMillis()); message.setSentDate(now); message.setSubject(now.toString()); message.setText("Test at " + now.toString()); sender.send(message); Operation op = getLastEntered(); assertNotNull("No operation extracted", op); assertEquals("Mismatched operation type", MailDefinitions.SEND_OPERATION, op.getType()); assertEquals("Mismatched protocol", sender.getProtocol(), op.get(MailDefinitions.SEND_PROTOCOL, String.class)); assertEquals("Mismatched host", sender.getHost(), op.get(MailDefinitions.SEND_HOST, String.class)); if (port == -1) { assertEquals("Mismatched default port", 25, op.getInt(MailDefinitions.SEND_PORT, (-1))); } else { assertEquals("Mismatched send port", sender.getPort(), op.getInt(MailDefinitions.SEND_PORT, (-1))); } if (getAspect().collectExtraInformation()) { assertAddresses(op, MailDefinitions.SEND_SENDERS, 1); assertAddresses(op, MailDefinitions.SEND_RECIPS, 3); OperationMap details = op.get(MailDefinitions.SEND_DETAILS, OperationMap.class); assertNotNull("No details extracted", details); assertEquals("Mismatched subject", message.getSubject(), details.get(MailDefinitions.SEND_SUBJECT, String.class)); } }
From source file:cz.zcu.kiv.eegdatabase.data.service.SpringJavaMailService.java
@Override public boolean sendForgottenPasswordMail(String email, String plainPassword) { log.debug("Creating new mail object"); SimpleMailMessage mail = new SimpleMailMessage(mailMessage); log.debug("Composing e-mail - TO: " + email); String subject = mail.getSubject() + " - Password reset"; log.debug("Composing e-mail - SUBJECT: " + subject); mail.setSubject(subject);/*from www . j av a2s . c o m*/ String text = "Your password for EEGbase portal was reset. Your new password (within brackets) is [" + plainPassword + "]\n\n" + "Please change the password after logging into system."; log.debug("Composing e-mail - TEXT: " + text); mail.setText(text); return sendEmail(email, mail.getSubject(), mail.getText()); }
From source file:cz.zcu.kiv.eegdatabase.logic.controller.myaccount.ApplyForWritingPermissionController.java
@Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException bindException) throws Exception { log.debug("Processing the form"); ApplyForWritingPermissionCommand afwpc = (ApplyForWritingPermissionCommand) command; log.debug("Loading Person object of actual logged user from database"); Person user = personDao.getPerson(ControllerUtils.getLoggedUserName()); log.debug("Composing e-mail message"); SimpleMailMessage mail = new SimpleMailMessage(mailMessage); mail.setFrom(user.getEmail());//from ww w. j a v a 2 s .c om log.debug("Loading list of supervisors"); List<Person> supervisors = personDao.getSupervisors(); String[] emails = new String[supervisors.size()]; int i = 0; for (Person supervisor : supervisors) { emails[i++] = supervisor.getEmail(); } mail.setTo(emails); log.debug("Setting subject to e-mail message"); mail.setSubject(mail.getSubject() + " - Write permission request from user " + user.getUsername()); String messageBody = "User " + user.getUsername() + " has requested permission for adding data into EEGbase system.\n" + "Reason is: " + afwpc.getReason() + "\n" + "Use the address below to grant the write permission.\n"; String linkAddress = "http://" + request.getLocalAddr() + ":" + request.getLocalPort() + request.getContextPath() + "/system/grant-permission.html?id=" + user.getPersonId(); log.debug("Address is: " + linkAddress); messageBody += linkAddress; mail.setText(messageBody); String mavName = ""; try { log.debug("Sending message"); mailSender.send(mail); log.debug("Mail was sent"); mavName = getSuccessView(); } catch (MailException e) { log.debug("Mail was not sent"); mavName = getFailView(); } log.debug("Returning MAV"); ModelAndView mav = new ModelAndView(mavName); return mav; }
From source file:cz.zcu.kiv.eegdatabase.logic.controller.root.ForgottenPasswordController.java
@Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException bindException) throws Exception { ForgottenPasswordCommand fpc = (ForgottenPasswordCommand) command; Person user = personDao.getPerson(fpc.getUsername()); log.debug("Creating new mail object"); SimpleMailMessage mail = new SimpleMailMessage(mailMessage); String recipient = user.getEmail(); log.debug("Composing e-mail - TO: " + recipient); mail.setTo(recipient);/* ww w.j a v a2s .com*/ String subject = mail.getSubject() + " - Password reset"; log.debug("Composing e-mail - SUBJECT: " + subject); mail.setSubject(subject); String password = ControllerUtils.getRandomPassword(); String text = "Your password for EEGbase portal was reset. Your new password (within brackets) is [" + password + "]\n\n" + "Please change the password after logging into system."; log.debug("Composing e-mail - TEXT: " + text); mail.setText(text); String mavName = getSuccessView(); try { log.debug("Sending e-mail message"); mailSender.send(mail); log.debug("E-mail message sent successfully"); log.debug("Updating new password into database"); user.setPassword(new BCryptPasswordEncoder().encode(password)); personDao.update(user); log.debug("Password updated"); } catch (MailException e) { log.debug("E-mail message was NOT sent"); log.debug("Password was NOT changed"); mavName = getFailedView(); } log.debug("Returning MAV"); ModelAndView mav = new ModelAndView(mavName); return mav; }
From source file:cz.zcu.kiv.eegdatabase.logic.controller.root.WriteRequestsListController.java
/** * Sends e-mail with granting message or rejecting message to the recipient * * @param recipient E-mail address of the recipient * @param grant If <code>true</code>, granting message will be sent, * if <code>false</code>, rejecting message will be sent *//*from w w w . java2 s . com*/ private boolean sendEmail(String recipient, boolean grant) { log.debug("Sending e-mail"); SimpleMailMessage mail = new SimpleMailMessage(mailMessage); mail.setTo(recipient); log.debug("Setting the parameters of the e-mail message"); String subject = ""; String text = ""; if (grant) { subject = mail.getSubject() + " - Write permission granted"; text = "Congratulation, the write permission for the EEGbase portal was granted. You can now submit your data. Thank you for your interest."; } else { subject = mail.getSubject() + " - Write permission rejected"; text = "We are sorry, but the write permission for the EEGbase portal was rejected. You can apply again, try to better explain your reasons. Thank you."; } mail.setSubject(subject); mail.setText(text); try { log.debug("Sending the e-mail"); mailSender.send(mail); log.debug("E-mail was sent"); return true; } catch (MailException e) { log.debug("E-mail was NOT sent"); return false; } }
From source file:org.medici.bia.service.mail.MailServiceImpl.java
/** * {@inheritDoc}// w w w. java2 s . c o m */ @Transactional(readOnly = false, propagation = Propagation.REQUIRED) @Override public Boolean sendForumPostReplyNotificationMessage(ForumPostNotified forumPostReplied, ForumPost forumPost, User currentUser) { try { if (!StringUtils.isBlank(currentUser.getMail())) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(getMailFrom()); message.setTo(currentUser.getMail()); if (!Forum.SubType.COURSE.equals(forumPost.getForum().getSubType())) { // message for a reply post message.setSubject(ApplicationPropertyManager .getApplicationProperty("mail.forumPostReplyNotification.subject", new String[] { forumPost.getUser().getFirstName(), forumPost.getUser().getLastName(), forumPost.getParentPost().getSubject() }, "{", "}")); message.setText(ApplicationPropertyManager.getApplicationProperty( "mail.forumPostReplyNotification.text", new String[] { forumPost.getUser().getFirstName(), forumPost.getUser().getLastName(), forumPost.getParentPost().getSubject(), getForumTopicUrl(forumPost.getTopic(), Forum.SubType.COURSE.equals(forumPost.getForum().getSubType())) }, "{", "}")); } else { // message for a course transcription post or a course question post message.setSubject(ApplicationPropertyManager .getApplicationProperty("mail.courseTranscriptionNotification.subject", new String[] { forumPost.getUser().getFirstName(), forumPost.getUser().getLastName(), forumPost.getTopic().getSubject() }, "{", "}")); CourseTopicOption courseTopicOption = getCourseTopicOptionDAO() .getOption(forumPost.getTopic().getTopicId()); message.setText(ApplicationPropertyManager.getApplicationProperty( "mail.courseTranscriptionNotification.text", new String[] { forumPost.getUser().getFirstName(), forumPost.getUser().getLastName(), forumPost.getTopic().getSubject(), getCourseTopicUrl(courseTopicOption) }, "{", "}")); } //getJavaMailSender().send(message); //instead of sending the message by email sending it by internal message // Composing Message UserMessage userMessage = new UserMessage(); userMessage.setSender("Staff"); User tempUser = currentUser; userMessage.setRecipient(tempUser.getAccount()); userMessage.setSubject(message.getSubject()); userMessage.setBody(message.getText()); userMessage.setMessageId(null); userMessage.setRecipientStatus(RecipientStatus.NOT_READ); userMessage.setSendedDate(new Date()); //Sending Message getCommunityService().createNewMessage(userMessage); } else { logger.error("Mail for ForumPost reply not sended for user " + currentUser.getAccount() + ". Check mail field on tblUser for account " + currentUser.getAccount()); } forumPostReplied.setMailSended(Boolean.TRUE); forumPostReplied.setMailSendedDate(new Date()); return Boolean.TRUE; } catch (Throwable throwable) { logger.error(throwable); return Boolean.FALSE; } }