List of usage examples for org.springframework.mail.javamail JavaMailSenderImpl createMimeMessage
@Override
public MimeMessage createMimeMessage()
From source file:org.syncope.core.scheduling.NotificationJob.java
public TaskExec executeSingle(final NotificationTask task) { init();//w w w . j av a2 s . co m TaskExec execution = new TaskExec(); execution.setTask(task); execution.setStartDate(new Date()); if (StringUtils.isBlank(smtpHost) || StringUtils.isBlank(task.getSender()) || 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" + smtpHost + ":" + smtpPort + "\n" + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject() + "\n" + task.getHtmlBody() + "\n" + task.getTextBody(); LOG.error(message); execution.setStatus(Status.NOT_SENT.name()); if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) { execution.setMessage(message); } } else { if (LOG.isDebugEnabled()) { LOG.debug("About to send e-mails:\n" + smtpHost + ":" + smtpPort + "\n" + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject() + "\n" + task.getHtmlBody() + "\n" + task.getTextBody() + "\n"); } for (String to : task.getRecipients()) { try { JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost(smtpHost); sender.setPort(smtpPort); if (StringUtils.isNotBlank(smtpUsername)) { sender.setUsername(smtpUsername); } if (StringUtils.isNotBlank(smtpPassword)) { sender.setPassword(smtpPassword); } MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setFrom(task.getSender()); helper.setSubject(task.getSubject()); helper.setText(task.getTextBody(), task.getHtmlBody()); sender.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()); } } catch (Throwable t) { LOG.error("Could not send e-mail", t); execution.setStatus(Status.NOT_SENT.name()); StringWriter exceptionWriter = new StringWriter(); exceptionWriter.write(t.getMessage() + "\n\n"); t.printStackTrace(new PrintWriter(exceptionWriter)); if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) { execution.setMessage(exceptionWriter.toString()); } } execution.setEndDate(new Date()); } } if (hasToBeRegistered(execution)) { execution = taskExecDAO.save(execution); } return execution; }
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 ww w .j a 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.akaza.openclinica.controller.SystemController.java
public String sendEmail(JavaMailSenderImpl mailSender, String emailSubject, String message) throws OpenClinicaSystemException { logger.info("Sending email..."); try {/*from ww w . j a va 2 s . c om*/ 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.mifosplatform.infrastructure.reportmailingjob.service.ReportMailingJobEmailServiceImpl.java
@Override public void sendEmailWithAttachment(ReportMailingJobEmailData reportMailingJobEmailData) { try {/*from w w w. ja va2s .co m*/ // get all ReportMailingJobConfiguration objects from the database this.reportMailingJobConfigurationDataCollection = this.reportMailingJobConfigurationReadPlatformService .retrieveAllReportMailingJobConfigurations(); JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl(); javaMailSenderImpl.setHost(this.getReportSmtpServer()); javaMailSenderImpl.setPort(this.getRerportSmtpPort()); javaMailSenderImpl.setUsername(this.getReportSmtpUsername()); javaMailSenderImpl.setPassword(this.getReportSmtpPassword()); javaMailSenderImpl.setJavaMailProperties(this.getJavaMailProperties()); MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage(); // use the true flag to indicate you need a multipart message MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setTo(reportMailingJobEmailData.getTo()); mimeMessageHelper.setFrom(this.getReportSmtpFromAddress()); mimeMessageHelper.setText(reportMailingJobEmailData.getText()); mimeMessageHelper.setSubject(reportMailingJobEmailData.getSubject()); if (reportMailingJobEmailData.getAttachment() != null) { mimeMessageHelper.addAttachment(reportMailingJobEmailData.getAttachment().getName(), reportMailingJobEmailData.getAttachment()); } javaMailSenderImpl.send(mimeMessage); } catch (MessagingException e) { // handle the exception e.printStackTrace(); } }
From source file:org.springframework.integration.samples.mailattachments.MimeMessageParsingTest.java
/** * This test will create a Mime Message that contains an Attachment, send it * to an SMTP Server (Using Wiser) and retrieve and process the Mime Message. * * This test verifies that the parsing of the retrieved Mime Message is * successful and that the correct number of {@link EmailFragment}s is created. *//*w ww . j av a 2s .co m*/ @Test public void testProcessingOfEmailAttachments() { final JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setPort(this.wiserPort); final MimeMessage message = mailSender.createMimeMessage(); final String pictureName = "picture.png"; final ByteArrayResource byteArrayResource = getFileData(pictureName); try { final MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom("testfrom@springintegration.org"); helper.setTo("testto@springintegration.org"); helper.setSubject("Parsing of Attachments"); helper.setText("Spring Integration Rocks!"); helper.addAttachment(pictureName, byteArrayResource, "image/png"); } catch (MessagingException e) { throw new MailParseException(e); } mailSender.send(message); final List<WiserMessage> wiserMessages = wiser.getMessages(); Assert.assertTrue(wiserMessages.size() == 1); boolean foundTextMessage = false; boolean foundPicture = false; for (WiserMessage wiserMessage : wiserMessages) { final List<EmailFragment> emailFragments = new ArrayList<EmailFragment>(); try { final MimeMessage mailMessage = wiserMessage.getMimeMessage(); EmailParserUtils.handleMessage(null, mailMessage, emailFragments); } catch (MessagingException e) { throw new IllegalStateException("Error while retrieving Mime Message."); } Assert.assertTrue(emailFragments.size() == 2); for (EmailFragment emailFragment : emailFragments) { if ("picture.png".equals(emailFragment.getFilename())) { foundPicture = true; } if ("message.txt".equals(emailFragment.getFilename())) { foundTextMessage = true; } } Assert.assertTrue(foundPicture); Assert.assertTrue(foundTextMessage); } }
From source file:org.springframework.integration.samples.mailattachments.MimeMessageParsingTest.java
/** * This test will create a Mime Message that in return contains another * mime message. The nested mime message contains an attachment. * * The root message consist of both HTML and Text message. * */// w ww.ja va 2s . co m @Test public void testProcessingOfNestedEmailAttachments() { final JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setPort(this.wiserPort); final MimeMessage rootMessage = mailSender.createMimeMessage(); try { final MimeMessageHelper messageHelper = new MimeMessageHelper(rootMessage, true); messageHelper.setFrom("testfrom@springintegration.org"); messageHelper.setTo("testto@springintegration.org"); messageHelper.setSubject("Parsing of Attachments"); messageHelper.setText("Spring Integration Rocks!", "Spring Integration <b>Rocks</b>!"); final String pictureName = "picture.png"; final ByteArrayResource byteArrayResource = getFileData(pictureName); messageHelper.addInline("picture12345", byteArrayResource, "image/png"); } catch (MessagingException e) { throw new MailParseException(e); } mailSender.send(rootMessage); final List<WiserMessage> wiserMessages = wiser.getMessages(); Assert.assertTrue(wiserMessages.size() == 1); boolean foundTextMessage = false; boolean foundPicture = false; boolean foundHtmlMessage = false; for (WiserMessage wiserMessage : wiserMessages) { List<EmailFragment> emailFragments = new ArrayList<EmailFragment>(); try { final MimeMessage mailMessage = wiserMessage.getMimeMessage(); EmailParserUtils.handleMessage(null, mailMessage, emailFragments); } catch (MessagingException e) { throw new IllegalStateException("Error while retrieving Mime Message."); } Assert.assertTrue(emailFragments.size() == 3); for (EmailFragment emailFragment : emailFragments) { if ("<picture12345>".equals(emailFragment.getFilename())) { foundPicture = true; } if ("message.txt".equals(emailFragment.getFilename())) { foundTextMessage = true; } if ("message.html".equals(emailFragment.getFilename())) { foundHtmlMessage = true; } } Assert.assertTrue(foundPicture); Assert.assertTrue(foundTextMessage); Assert.assertTrue(foundHtmlMessage); } }
From source file:org.thingsboard.server.service.mail.DefaultMailService.java
private void sendMail(JavaMailSenderImpl mailSender, String mailFrom, String email, String subject, String message) throws ThingsboardException { try {// w w w. ja v a 2 s .c om MimeMessage mimeMsg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, UTF_8); helper.setFrom(mailFrom); helper.setTo(email); helper.setSubject(subject); helper.setText(message, true); mailSender.send(helper.getMimeMessage()); } catch (Exception e) { throw handleException(e); } }
From source file:org.yes.cart.service.mail.impl.MailComposerImplTest.java
@Test public void testComposeMimeMessageInternalTextAndHtmlVersion() throws MessagingException, IOException, ClassNotFoundException { // of course you would use DI in any real-world cases JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("localhost"); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); String textTemplate = "$name lives in theme park with <% with.each{ out.print(it + ' ');}%>"; String htmlTemplate = "<h2>$name</h2> lives in theme park with:<br> <% with.each{ out.print(it + '<br>');}%>"; MailComposerImpl mailComposer = new MailComposerImpl(null); mailComposer.composeMessage(helper, textTemplate, htmlTemplate, Collections.EMPTY_LIST, "SHOP10", "en", "test", createModel()); assertTrue(helper.isMultipart());//from ww w . j a va 2s . co m ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); helper.getMimeMessage().writeTo(byteArrayOutputStream); String str = byteArrayOutputStream.toString("UTF-8"); assertNotNull(str); // html and text present in mail message assertTrue(str.contains("Bender lives in theme park with blackjack poetess")); assertTrue(str.contains("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>")); }
From source file:org.yes.cart.service.mail.impl.MailComposerImplTest.java
/** * Text template only//from w w w . j a v a 2 s . c o m */ @Test public void testComposeMimeMessageInternalTextVersionOnly() throws MessagingException, IOException, ClassNotFoundException { // of course you would use DI in any real-world cases JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("localhost"); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); String textTemplate = "$name lives in theme park with <% with.each{ out.print(it + ' ');}%>"; String htmlTemplate = null; MailComposerImpl mailComposer = new MailComposerImpl(null); mailComposer.composeMessage(helper, textTemplate, htmlTemplate, Collections.EMPTY_LIST, "SHOP10", "en", "test", createModel()); assertTrue(helper.isMultipart()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); helper.getMimeMessage().writeTo(byteArrayOutputStream); String str = byteArrayOutputStream.toString("UTF-8"); assertNotNull(str); // html and text present in mail message assertTrue(str.contains("Bender lives in theme park with blackjack poetess")); }
From source file:org.yes.cart.service.mail.impl.MailComposerImplTest.java
/** * html only// w w w . ja v a 2s . co m */ @Test public void testComposeMimeMessageInternalHtmlVersionOnly() throws MessagingException, IOException, ClassNotFoundException { // of course you would use DI in any real-world cases JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("localhost"); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); String textTemplate = null; String htmlTemplate = "<h2>$name</h2> lives in theme park with:<br> <% with.each{ out.print(it + '<br>');}%>"; MailComposerImpl mailComposer = new MailComposerImpl(null); mailComposer.composeMessage(helper, textTemplate, htmlTemplate, Collections.EMPTY_LIST, "SHOP10", "en", "test", createModel()); assertTrue(helper.isMultipart()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); helper.getMimeMessage().writeTo(byteArrayOutputStream); String str = byteArrayOutputStream.toString("UTF-8"); assertNotNull(str); // html and text present in mail message assertTrue(str.contains("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>")); }