List of usage examples for javax.mail.internet MimeMessage writeTo
@Override public void writeTo(OutputStream os) throws IOException, MessagingException
From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java
public MimeMessage transform(MimeMessage message) throws MessagingException { MimeBodyPart sentToBodyPart = newSentToBodyPart(message); MimeBodyPart originalBodyPart = newOriginalBodyPart(message); // create a new multipart content for this message. MimeMultipart multipart = new MimeMultipart(EmailUtil.SUBTYPE_MIXED); // add the parts to the body. multipart.addBodyPart(originalBodyPart); multipart.addBodyPart(sentToBodyPart); // get the new values for all of the headers. InternetAddress newFromAddress = newFromAddress(message); InternetAddress[] newToAddresses = newToAddresses(message); InternetAddress[] newCcAddresses = newCcAddresses(message); InternetAddress[] newBccAddresses = newBccAddresses(message); String newSubject = newSubject(message); // update the message. message.setFrom(newFromAddress);//from ww w.ja v a 2s . co m message.setRecipients(Message.RecipientType.TO, newToAddresses); message.setRecipients(Message.RecipientType.CC, newCcAddresses); message.setRecipients(Message.RecipientType.BCC, newBccAddresses); message.setSubject(newSubject); message.setContent(multipart); // save the message. message.saveChanges(); if (getLogProperty()) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); message.writeTo(out); log.info("Email Message Sent:\n{}", out.toString()); } catch (IOException ioe) { throw new MessagingException("Exception thrown while writing message to log.", ioe); } } if (!getSendProperty()) { message = null; } // return the message. return message; }
From source file:org.eurekaclinical.user.service.email.FreeMarkerEmailSender.java
/** * Send an email to the given email address with the given subject line, * using contents generated from the given template and parameters. * * @param templateName The name of the template used to generate the * contents of the email./* ww w. j a v a 2s. c o m*/ * @param subject The subject for the email being sent. * @param emailAddress Sends the email to this address. * @param params The template is merged with these parameters to generate * the content of the email. * @throws EmailException Thrown if there are any errors in generating * content from the template, composing the email, or sending the email. */ private void sendMessage(final String templateName, final String subject, final String emailAddress, final Map<String, Object> params) throws EmailException { Writer stringWriter = new StringWriter(); try { Template template = this.configuration.getTemplate(templateName); template.process(params, stringWriter); } catch (TemplateException | IOException e) { throw new EmailException(e); } String content = stringWriter.toString(); MimeMessage message = new MimeMessage(this.session); try { InternetAddress fromEmailAddress = null; String fromEmailAddressStr = this.userServiceProperties.getFromEmailAddress(); if (fromEmailAddressStr != null) { fromEmailAddress = new InternetAddress(fromEmailAddressStr); } if (fromEmailAddress == null) { fromEmailAddress = InternetAddress.getLocalAddress(this.session); } if (fromEmailAddress == null) { try { fromEmailAddress = new InternetAddress( "no-reply@" + InetAddress.getLocalHost().getCanonicalHostName()); } catch (UnknownHostException ex) { fromEmailAddress = new InternetAddress("no-reply@localhost"); } } message.setFrom(fromEmailAddress); message.setSubject(subject); message.setContent(content, "text/plain"); message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress)); message.setSender(fromEmailAddress); Transport.send(message); } catch (MessagingException e) { LOGGER.error("Error sending the following email message:"); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { message.writeTo(out); out.close(); } catch (IOException | MessagingException ex) { try { out.close(); } catch (IOException ignore) { } } LOGGER.error(out.toString()); throw new EmailException(e); } }
From source file:com.formkiq.web.WorkflowAddControllerIntegrationTest.java
/** * Verify Completion Email.//from w ww .j a va 2s. com * @throws IOException IOException * @throws MessagingException MessagingException */ private void verifyCompleteEmail() throws IOException, MessagingException { assertEquals(0, getMailSender().getMessages().size()); assertEquals(1, getMailSender().getMimeMessages().size()); MimeMessage msg = getMailSender().getMimeMessages().get(0); assertEquals("Completed signing Sample WF", msg.getSubject()); assertEquals("test@formkiq.com", msg.getAllRecipients()[0].toString()); Multipart multipart = (Multipart) msg.getContent(); assertEquals(1, multipart.getCount()); ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); String s = out.toString(CHARSET_UTF8.name()); assertFalse(s.contains("${sendername}")); assertFalse(s.contains("${signername}")); assertFalse(s.contains("${doc}")); assertFalse(s.contains("${stoken}")); assertTrue(s.contains("has reviewed and signed the document")); out.close(); }
From source file:com.formkiq.web.WorkflowAddControllerIntegrationTest.java
/** * verify email is sent for signing.//ww w . jav a2 s . c om * @return {@link String} The signing URL. * @throws IOException IOException * @throws MessagingException MessagingException */ private String verifyDocsignEmail() throws IOException, MessagingException { assertEquals(0, getMailSender().getMessages().size()); assertEquals(1, getMailSender().getMimeMessages().size()); MimeMessage msg = getMailSender().getMimeMessages().get(0); assertTrue(msg.getSubject().endsWith("sign this")); assertTrue(msg.getAllRecipients()[0].toString().endsWith("jacksmith@formkiq.com")); Multipart multipart = (Multipart) msg.getContent(); assertEquals(1, multipart.getCount()); ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); String s = out.toString(CHARSET_UTF8.name()); assertTrue(s.contains("John Smith")); assertTrue(s.contains("Jack Smith")); assertFalse(s.contains("${sendername}")); assertFalse(s.contains("${signername}")); assertFalse(s.contains("${doc}")); assertFalse(s.contains("${stoken}")); assertTrue(s.contains("Please review the document and sign at the link above")); out.close(); getMailSender().reset(); return findHrefUrl(s); }
From source file:org.sakaiproject.kernel.messaging.email.EmailMessageListener.java
public void handleMessage(Message email) throws AddressException, UnsupportedEncodingException, SendFailedException, MessagingException, IOException { String fromAddress = email.getHeader(Message.Field.FROM); if (fromAddress == null) { throw new MessagingException("Unable to send without a 'from' address."); }// w ww . j av a 2s. c o m // transform to a MimeMessage ArrayList<String> invalids = new ArrayList<String>(); // convert and validate the 'from' address InternetAddress from = new InternetAddress(fromAddress, true); // convert and validate reply to addresses String replyTos = email.getHeader(EmailMessage.Field.REPLY_TO); InternetAddress[] replyTo = emails2Internets(replyTos, invalids); // convert and validate the 'to' addresses String tos = email.getHeader(Message.Field.TO); InternetAddress[] to = emails2Internets(tos, invalids); // convert and validate 'cc' addresses String ccs = email.getHeader(EmailMessage.Field.CC); InternetAddress[] cc = emails2Internets(ccs, invalids); // convert and validate 'bcc' addresses String bccs = email.getHeader(EmailMessage.Field.BCC); InternetAddress[] bcc = emails2Internets(bccs, invalids); int totalRcpts = to.length + cc.length + bcc.length; if (totalRcpts == 0) { throw new MessagingException("No recipients to send to."); } MimeMessage mimeMsg = new MimeMessage(session); mimeMsg.setFrom(from); mimeMsg.setReplyTo(replyTo); mimeMsg.setRecipients(RecipientType.TO, to); mimeMsg.setRecipients(RecipientType.CC, cc); mimeMsg.setRecipients(RecipientType.BCC, bcc); // add in any additional headers Map<String, String> headers = email.getHeaders(); if (headers != null && !headers.isEmpty()) { for (Entry<String, String> header : headers.entrySet()) { mimeMsg.setHeader(header.getKey(), header.getValue()); } } // add the content to the message List<Message> parts = email.getParts(); if (parts == null || parts.size() == 0) { setContent(mimeMsg, email); } else { // create a multipart container Multipart multipart = new MimeMultipart(); // create a body part for the message text MimeBodyPart msgBodyPart = new MimeBodyPart(); setContent(msgBodyPart, email); // add the message part to the container multipart.addBodyPart(msgBodyPart); // add attachments for (Message part : parts) { addPart(multipart, part); } // set the multipart container as the content of the message mimeMsg.setContent(multipart); } if (allowTransport) { // send Transport.send(mimeMsg); } else { try { ByteArrayOutputStream output = new ByteArrayOutputStream(); mimeMsg.writeTo(output); String emailString = output.toString(); LOG.info(emailString); observable.notifyObservers(emailString); } catch (IOException e) { LOG.info("Transport disabled and unable to write message to log: " + e.getMessage(), e); } } }
From source file:org.liveSense.service.email.EmailServiceImpl.java
/** * {@inheritDoc}//from w w w.ja v a2s .c o m */ @Override public void sendEmail(Session session, final MimeMessage message) throws Exception { boolean haveSession = false; try { if (session != null && session.isLive()) { haveSession = true; } else { session = repository.loginAdministrative(null); } // Store mail to Spool folder Node mailNode = session.getRootNode().getNode(spoolFolder).addNode(UUID.randomUUID().toString(), nodeType); mailNode = mailNode.addNode(propertyName, "nt:resource"); PipedInputStream in = new PipedInputStream(); final PipedOutputStream out = new PipedOutputStream(in); new Thread(new Runnable() { @Override public void run() { try { message.writeTo(out); out.close(); } catch (IOException e) { log.error("Could not write mail message stream", e); } catch (MessagingException e) { log.error("Could not write mail message stream", e); } } }).start(); BinaryValue bv = null; try { bv = new BinaryValue(in); } catch (IllegalArgumentException e) { // The jackrabbit closes the PipedInputStream, thats incorrect } if (bv != null) { mailNode.setProperty("jcr:data", bv); } mailNode.setProperty("jcr:lastModified", Calendar.getInstance()); mailNode.setProperty("jcr:mimeType", "message/rfc822"); } catch (Exception ex) { log.error("Cannot create mail: ", ex); throw ex; } finally { if (!haveSession && session != null) { if (session.hasPendingChanges()) try { session.save(); } catch (Throwable th) { } session.logout(); } } }
From source file:org.apache.james.smtpserver.SMTPServerTest.java
public void verifyLastMail(String sender, String recipient, MimeMessage msg) throws IOException, MessagingException { Mail mailData = queue.getLastMail(); assertNotNull("mail received by mail server", mailData); if (sender == null && recipient == null && msg == null) { fail("no verification can be done with all arguments null"); }//from w w w . ja va2 s . c o m if (sender != null) { assertEquals("sender verfication", sender, mailData.getSender().toString()); } if (recipient != null) { assertTrue("recipient verfication", mailData.getRecipients().contains(new MailAddress(recipient))); } if (msg != null) { ByteArrayOutputStream bo1 = new ByteArrayOutputStream(); msg.writeTo(bo1); ByteArrayOutputStream bo2 = new ByteArrayOutputStream(); mailData.getMessage().writeTo(bo2); assertEquals(bo1.toString(), bo2.toString()); assertEquals("message verification", msg, mailData.getMessage()); } }
From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java
@Test public void testEncryptBase64EncodeBug() throws Exception { MimeMessage message = new MimeMessage(MailSession.getDefaultSession()); message.setSubject("test"); message.setContent("test", "text/plain"); SMIMEBuilder builder = new SMIMEBuilderImpl(message, "to", "subject", "from"); X509Certificate certificate = TestUtils .loadCertificate("test/resources/testdata/certificates/certificate-base64-encode-bug.cer"); builder.addRecipient(certificate, SMIMERecipientMode.ISSUER_SERIAL); builder.encrypt(SMIMEEncryptionAlgorithm.DES_EDE3_CBC); MimeMessage newMessage = builder.buildMessage(); newMessage.saveChanges();/* w w w.j a v a2 s .co m*/ File file = new File(tempDir, "testEncryptBase64EncodeBug.eml"); FileOutputStream output = new FileOutputStream(file); MailUtils.writeMessage(newMessage, output); newMessage = MailUtils.loadMessage(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); newMessage.writeTo(new SkipHeadersOutputStream(bos)); String blob = new String(bos.toByteArray(), "us-ascii"); // check if all lines are not longer than 76 characters LineIterator it = IOUtils.lineIterator(new StringReader(blob)); while (it.hasNext()) { String next = it.nextLine(); if (next.length() > 76) { fail("Line length exceeds 76: " + next); } } }
From source file:davmail.exchange.ews.EwsExchangeSession.java
@Override public void createMessage(String folderPath, String messageName, HashMap<String, String> properties, MimeMessage mimeMessage) throws IOException { EWSMethod.Item item = new EWSMethod.Item(); item.type = "Message"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {//from ww w . j a v a2 s. co m mimeMessage.writeTo(baos); } catch (MessagingException e) { throw new IOException(e.getMessage()); } baos.close(); item.mimeContent = Base64.encodeBase64(baos.toByteArray()); List<FieldUpdate> fieldUpdates = buildProperties(properties); if (!properties.containsKey("draft")) { // need to force draft flag to false if (properties.containsKey("read")) { fieldUpdates.add(Field.createFieldUpdate("messageFlags", "1")); } else { fieldUpdates.add(Field.createFieldUpdate("messageFlags", "0")); } } fieldUpdates.add(Field.createFieldUpdate("urlcompname", messageName)); item.setFieldUpdates(fieldUpdates); CreateItemMethod createItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, getFolderId(folderPath), item); executeMethod(createItemMethod); }
From source file:davmail.exchange.ews.EwsExchangeSession.java
@Override public void sendMessage(MimeMessage mimeMessage) throws IOException, MessagingException { String itemClass = null;//from ww w .j a va 2 s. c om if (mimeMessage.getContentType().startsWith("multipart/report")) { itemClass = "REPORT.IPM.Note.IPNRN"; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { mimeMessage.writeTo(baos); } catch (MessagingException e) { throw new IOException(e.getMessage()); } sendMessage(itemClass, baos.toByteArray()); }