List of usage examples for javax.mail.internet MimeMessage getContent
@Override public Object getContent() throws IOException, MessagingException
From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java
private void addEmailAttachmentsToJob(final DepositEmailConfiguration depositEmailConfiguration, final MimeMessage mimeMessage, final MultiFilesJob job) throws MessagingException, IOException, FileNotFoundException { final String jobConfigurationFileName = depositEmailConfiguration.getJobConfigurationFileName(); if (StringUtils.isNotBlank(jobConfigurationFileName)) { final File jobConfigurationFile = getJobConfigurationFile( depositEmailConfiguration.getApplicationName(), jobConfigurationFileName); job.addFile(Constants.MULTIPLE_FILES_JOB_CONFIGURATION, new FileInputStream(jobConfigurationFile)); }/*from w w w .ja va 2s. c o m*/ final Object content = mimeMessage.getContent(); Validate.isTrue(content instanceof Multipart, "only multipart emails can be processed"); final Multipart multipart = (Multipart) content; for (int i = 0, n = multipart.getCount(); i < n; i++) { final Part part = multipart.getBodyPart(i); final String disposition = part.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) { final String name = part.getFileName(); final String contentType = StringUtils.substringBefore(part.getContentType(), ";"); MultiFilesJob.addDataToJob(contentType, name, part.getInputStream(), job); } } }
From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
private EmailMessage wrapMessage(Message msg, boolean populateContent, Session session) throws MessagingException, IOException, ScanException, PolicyException { // Prepare subject String subject = msg.getSubject(); if (!StringUtils.isBlank(subject)) { AntiSamy as = new AntiSamy(); CleanResults cr = as.scan(subject, policy); subject = cr.getCleanHTML();/*w w w .ja va 2 s.c o m*/ } // Prepare content if requested EmailMessageContent msgContent = null; // default... if (populateContent) { // Defend against the dreaded: "Unable to load BODYSTRUCTURE" try { msgContent = getMessageContent(msg.getContent(), msg.getContentType()); } catch (MessagingException me) { // We are unable to read digitally-signed messages (perhaps // others?) in the API-standard way; we have to use a work around. // See: http://www.oracle.com/technetwork/java/faq-135477.html#imapserverbug // Logging as DEBUG because this behavior is known & expected. log.debug("Difficulty reading a message (digitally signed?). Attempting workaround..."); try { MimeMessage mm = (MimeMessage) msg; ByteArrayOutputStream bos = new ByteArrayOutputStream(); mm.writeTo(bos); bos.close(); SharedByteArrayInputStream bis = new SharedByteArrayInputStream(bos.toByteArray()); MimeMessage copy = new MimeMessage(session, bis); bis.close(); msgContent = getMessageContent(copy.getContent(), copy.getContentType()); } catch (Throwable t) { log.error("Failed to read message body", t); msgContent = new EmailMessageContent("UNABLE TO READ MESSAGE BODY: " + t.getMessage(), false); } } // Sanitize with AntiSamy String content = msgContent.getContentString(); if (!StringUtils.isBlank(content)) { AntiSamy as = new AntiSamy(); CleanResults cr = as.scan(content, policy); content = cr.getCleanHTML(); } msgContent.setContentString(content); } int messageNumber = msg.getMessageNumber(); // Prepare the UID if present String uid = null; // default if (msg.getFolder() instanceof UIDFolder) { uid = Long.toString(((UIDFolder) msg.getFolder()).getUID(msg)); } Address[] addr = msg.getFrom(); String sender = getFormattedAddresses(addr); Date sentDate = msg.getSentDate(); boolean unread = !msg.isSet(Flag.SEEN); boolean answered = msg.isSet(Flag.ANSWERED); boolean deleted = msg.isSet(Flag.DELETED); // Defend against the dreaded: "Unable to load BODYSTRUCTURE" boolean multipart = false; // sensible default; String contentType = null; // sensible default try { multipart = msg.getContentType().toLowerCase().startsWith(CONTENT_TYPE_ATTACHMENTS_PATTERN); contentType = msg.getContentType(); } catch (MessagingException me) { // Message was digitally signed and we are unable to read it; // logging as DEBUG because this issue is known/expected, and // because the user's experience is in no way affected (at this point) log.debug("Message content unavailable (digitally signed?); " + "message will appear in the preview table correctly, " + "but the body will not be viewable"); log.trace(me.getMessage(), me); } String to = getTo(msg); String cc = getCc(msg); String bcc = getBcc(msg); return new EmailMessage(messageNumber, uid, sender, subject, sentDate, unread, answered, deleted, multipart, contentType, msgContent, to, cc, bcc); }
From source file:ca.airspeed.demo.testingemail.EmailServiceTest.java
/** * When we send out an email with just a text body, et expect to get a * Multipart email having only a plain text body. */// w ww. j a v a 2 s . c o m @Test public void testSimpleEmail() throws Exception { // Given: EmailService service = makeALocalMailer(); InternetAddress expectedTo = new InternetAddress("Indiana.Jones@domain.com", "Indiana Jones"); String expectedSubject = "This is a Test Email"; String expectedTextBody = "This is a simple test."; // When: service.sendSimpleEmail(expectedTo, expectedSubject, expectedTextBody); // Then: List<WiserMessage> messages = wiser.getMessages(); assertEquals("Number of messages sent;", 1, messages.size()); WiserMessage message = messages.get(0); assertNotNull("No message was actually sent.", message); MimeMessage mimeMessage = message.getMimeMessage(); Address[] toRecipients = mimeMessage.getRecipients(RecipientType.TO); assertEquals("Number of To: Recipient;", 1, toRecipients.length); Address toRecipient = toRecipients[0]; assertEquals("To: Recipient;", expectedTo, toRecipient); InternetAddress expectedFrom = new InternetAddress("admin@domain.com", "Domain Admin"); Address[] fromArr = mimeMessage.getFrom(); assertEquals("From: email addresses;", 1, fromArr.length); assertEquals("Email From: address,", expectedFrom, fromArr[0]); assertEquals("Subject;", expectedSubject, mimeMessage.getSubject()); assertNotNull("The date of the email cannot be null.", mimeMessage.getSentDate()); MimeMultipart body = ((MimeMultipart) mimeMessage.getContent()); assertEquals("Number of MIME Parts in the body;", 1, body.getCount()); MimeMultipart textPart = ((MimeMultipart) body.getBodyPart(0).getContent()); assertEquals("Number of MIME parts in the text body;", 1, textPart.getCount()); MimeBodyPart plainTextPart = ((MimeBodyPart) textPart.getBodyPart(0)); assertTrue("Expected the plain text content to be text/plain.", plainTextPart.isMimeType("text/plain")); assertEquals("Text Body;", expectedTextBody, plainTextPart.getContent()); }
From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java
private void encrypt(String algorithm, KeyStoreKeyProvider keyStore) throws Exception { MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message.eml")); MockMailetConfig mailetConfig = new MockMailetConfig("test"); mailetConfig.setInitParameter("algorithm", "3DES"); mailetConfig.setInitParameter("algorithmAttribute", "algorithm"); SMIMEEncrypt mailet = new SMIMEEncrypt(); mailet.init(mailetConfig);// w w w.j a v a 2 s .co m Mail mail = new MockMail(); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("test@example.com")); mail.setRecipients(recipients); DjigzoMailAttributesImpl mailAttributes = new DjigzoMailAttributesImpl(mail); mailAttributes.setCertificates(certificates); mail.setAttribute("algorithm", algorithm); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), keyStore, "BC"); assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType()); assertEquals(SMIMEEncryptionAlgorithm.fromName(algorithm).getOID().toString(), inspector.getEnvelopedInspector().getEncryptionAlgorithmOID()); assertEquals(20, inspector.getEnvelopedInspector().getRecipients().size()); MimeMessage decrypted = inspector.getContentAsMimeMessage(); assertEquals("test", ((String) decrypted.getContent()).trim()); }
From source file:gr.abiss.calipso.mail.MailSender.java
/** * we bend the rules a little and fire off a new thread for sending * an email message. This has the advantage of not slowing down the item * create and update screens, i.e. the system returns the next screen * after "submit" without blocking. This has been used in production * for quite a while now, on Tomcat without any problems. This helps a lot * especially when the SMTP server is slow to respond, etc. *//*from w ww . j ava 2 s . c o m*/ private void sendInNewThread(final MimeMessage message) { // try { // logger.info("Sending message: " + message.getSubject() + "\n" + message.getContent()); // } catch (MessagingException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } catch (IOException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } if (logger.isDebugEnabled()) { try { logger.debug("Message contenttype: " + message.getContentType()); logger.debug("Message content: " + message.getContent()); Enumeration headers = message.getAllHeaders(); logger.debug("Message Headers..."); while (headers.hasMoreElements()) { Header h = (Header) headers.nextElement(); logger.error(h.getName() + ": " + h.getValue()); } logger.debug("Message flags: " + message.getFlags()); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } new Thread() { @Override public void run() { logger.debug("send mail thread start"); try { try { sender.send(message); logger.debug("send mail thread successfull"); } catch (Exception e) { logger.error("send mail thread failed, dumping headers: "); logger.error("mail headers dump start"); Enumeration headers = message.getAllHeaders(); while (headers.hasMoreElements()) { Header h = (Header) headers.nextElement(); logger.error(h.getName() + ": " + h.getValue()); } logger.error("mail headers dump end, exception follows", e); } } catch (Exception e) { throw new RuntimeException(e); } } }.start(); }
From source file:cherry.foundation.mail.MailSendHandlerImplTest.java
@Test public void testSendNowAttached() throws Exception { LocalDateTime now = LocalDateTime.now(); MailSendHandler handler = create(now); ArgumentCaptor<MimeMessagePreparator> preparator = ArgumentCaptor.forClass(MimeMessagePreparator.class); doNothing().when(mailSender).send(preparator.capture()); final File file = File.createTempFile("test_", ".txt", new File(".")); file.deleteOnExit();// www . j av a 2 s . com try { try (OutputStream out = new FileOutputStream(file)) { out.write("attach2".getBytes()); } final DataSource dataSource = new DataSource() { @Override public OutputStream getOutputStream() throws IOException { return null; } @Override public String getName() { return "name3.txt"; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream("attach3".getBytes()); } @Override public String getContentType() { return "text/plain"; } }; long messageId = handler.sendNow("loginId", "messageName", "from@addr", asList("to@addr"), asList("cc@addr"), asList("bcc@addr"), "subject", "body", new AttachmentPreparator() { @Override public void prepare(Attachment attachment) throws MessagingException { attachment.add("name0.txt", new ByteArrayResource("attach0".getBytes())); attachment.add("name1.bin", new ByteArrayResource("attach1".getBytes()), "application/octet-stream"); attachment.add("name2.txt", file); attachment.add("name3.txt", dataSource); } }); Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); preparator.getValue().prepare(message); assertEquals(0L, messageId); assertEquals(1, message.getRecipients(RecipientType.TO).length); assertEquals(parse("to@addr")[0], message.getRecipients(RecipientType.TO)[0]); assertEquals(1, message.getRecipients(RecipientType.CC).length); assertEquals(parse("cc@addr")[0], message.getRecipients(RecipientType.CC)[0]); assertEquals(1, message.getRecipients(RecipientType.BCC).length); assertEquals(parse("bcc@addr")[0], message.getRecipients(RecipientType.BCC)[0]); assertEquals(1, message.getFrom().length); assertEquals(parse("from@addr")[0], message.getFrom()[0]); assertEquals("subject", message.getSubject()); MimeMultipart mm = (MimeMultipart) message.getContent(); assertEquals(5, mm.getCount()); assertEquals("body", ((MimeMultipart) mm.getBodyPart(0).getContent()).getBodyPart(0).getContent()); assertEquals("name0.txt", mm.getBodyPart(1).getFileName()); assertEquals("text/plain", mm.getBodyPart(1).getContentType()); assertEquals("attach0", mm.getBodyPart(1).getContent()); assertEquals("name1.bin", mm.getBodyPart(2).getDataHandler().getName()); assertEquals("application/octet-stream", mm.getBodyPart(2).getDataHandler().getContentType()); assertEquals("attach1", new String( ByteStreams.toByteArray((InputStream) mm.getBodyPart(2).getDataHandler().getContent()))); assertEquals("name2.txt", mm.getBodyPart(3).getFileName()); assertEquals("text/plain", mm.getBodyPart(3).getContentType()); assertEquals("attach2", mm.getBodyPart(3).getContent()); assertEquals("name3.txt", mm.getBodyPart(4).getFileName()); assertEquals("text/plain", mm.getBodyPart(4).getContentType()); assertEquals("attach3", mm.getBodyPart(4).getContent()); } finally { file.delete(); } }
From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java
@Test public void testMultipartWithIllegalContentTransferEncoding() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); mailetConfig.setInitParameter("algorithm", "AES128"); SMIMEEncrypt mailet = new SMIMEEncrypt(); mailet.init(mailetConfig);//w w w . ja v a 2 s . c o m Mail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/quoted-printable-multipart.eml")); assertTrue(message.isMimeType("multipart/mixed")); MimeMultipart mp = (MimeMultipart) message.getContent(); assertEquals(2, mp.getCount()); BodyPart part = mp.getBodyPart(0); assertTrue(part.isMimeType("text/plain")); assertEquals("==", (String) part.getContent()); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("test@example.com")); mail.setRecipients(recipients); DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail); mailAttributes.setCertificates(certificates); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); KeyStoreKeyProvider keyStore = new KeyStoreKeyProvider( loadKeyStore(new File("test/resources/testdata/keys/testCertificates.p12"), "test"), "test"); SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), keyStore, "BC"); assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType()); assertEquals(SMIMEEncryptionAlgorithm.AES128_CBC.getOID().toString(), inspector.getEnvelopedInspector().getEncryptionAlgorithmOID()); assertEquals(20, inspector.getEnvelopedInspector().getRecipients().size()); MimeMessage decrypted = inspector.getContentAsMimeMessage(); decrypted.saveChanges(); assertNotNull(decrypted); MailUtils.writeMessage(decrypted, new File(tempDir, "testMultipartWithIllegalContentTransferEncoding.eml")); assertTrue(decrypted.isMimeType("multipart/mixed")); mp = (MimeMultipart) decrypted.getContent(); assertEquals(2, mp.getCount()); part = mp.getBodyPart(0); assertTrue(part.isMimeType("text/plain")); /* * The body should not be changed to =3D=3D because the body should not be quoted-printable encoded * again */ assertEquals("==", (String) part.getContent()); }
From source file:mitm.application.djigzo.james.mailets.NotifyTest.java
@Test public void testSpecialUserPropertyRecipient() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); String template = FileUtils.readFileToString(new File("test/resources/templates/test-user-property.ftl")); autoTransactDelegator.setProperty("test@example.com", "notifyTemplate", template); autoTransactDelegator.setProperty("test@EXAMPLE.com", "prop.recipient", "recipient.from.property@example.com, Martijn Brinkers <martijn@djigzo.com>"); Notify mailet = new Notify(); mailetConfig.setInitParameter("template", "encryption-notification.ftl"); mailetConfig.setInitParameter("templateProperty", "notifyTemplate"); mailetConfig.setInitParameter("recipients", "${originator}, #{prop.recipient}"); mailet.init(mailetConfig);/* w w w. ja v a 2 s. c o m*/ MockMail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message.eml")); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("m.brinkers@pobox.com")); recipients.add(new MailAddress("123@example.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("test@example.com")); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); assertEquals(1, listener.getSenders().size()); assertEquals(1, listener.getRecipients().size()); assertEquals(1, listener.getStates().size()); assertEquals(1, listener.getMessages().size()); assertEquals(1, listener.getMails().size()); assertEquals("test@example.com,recipient.from.property@example.com,martijn@djigzo.com", StringUtils.join(listener.getRecipients().get(0), ",")); MimeMessage notification = listener.getMessages().get(0); MailUtils.validateMessage(notification); String content = (String) notification.getContent(); assertEquals("property 1 not set\nproperty 2 not set\nnon existing property not set\n", content); }
From source file:mitm.application.djigzo.james.mailets.NotifyTest.java
@Test public void testSpecialUserPropertyRecipientUnknown() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); String template = FileUtils.readFileToString(new File("test/resources/templates/test-user-property.ftl")); autoTransactDelegator.setProperty("test@example.com", "notifyTemplate", template); Notify mailet = new Notify(); mailetConfig.setInitParameter("template", "encryption-notification.ftl"); mailetConfig.setInitParameter("templateProperty", "notifyTemplate"); mailetConfig.setInitParameter("recipients", "${replyTo}, #{prop.recipient}"); mailet.init(mailetConfig);// w ww. j a va 2s . c o m MockMail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/chinese-text.eml")); message.setFrom(new InternetAddress("test@example.com")); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("123@example.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("test@example.com")); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); assertEquals("[123@example.com]", MailAddressUtils.getRecipients(mail).toString()); assertTrue(TestUtils.isEqual(message, mail.getMessage())); assertEquals(1, listener.getSenders().size()); assertEquals(1, listener.getRecipients().size()); assertEquals(1, listener.getStates().size()); assertEquals(1, listener.getMessages().size()); assertEquals(1, listener.getMails().size()); assertEquals("[users@tapestry.apache.org]", listener.getRecipients().get(0).toString()); MimeMessage notification = listener.getMessages().get(0); MailUtils.validateMessage(notification); String content = (String) notification.getContent(); assertEquals("property 1 not set\nproperty 2 not set\nnon existing property not set\n", content); }
From source file:mitm.application.djigzo.james.mailets.NotifyTest.java
@Test public void testSpecialUserPropertyRecipientInvalidEmail() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); String template = FileUtils.readFileToString(new File("test/resources/templates/test-user-property.ftl")); autoTransactDelegator.setProperty("test@example.com", "notifyTemplate", template); autoTransactDelegator.setProperty("test@EXAMPLE.com", "prop.recipient", "INVALID, martijn@djigzo.com"); Notify mailet = new Notify(); mailetConfig.setInitParameter("template", "encryption-notification.ftl"); mailetConfig.setInitParameter("templateProperty", "notifyTemplate"); mailetConfig.setInitParameter("recipients", "${originator}, #{prop.recipient}"); mailet.init(mailetConfig);//www . j ava 2 s. c om MockMail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message.eml")); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("m.brinkers@pobox.com")); recipients.add(new MailAddress("123@example.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("test@example.com")); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); assertEquals("[123@example.com, m.brinkers@pobox.com]", MailAddressUtils.getRecipients(mail).toString()); assertTrue(TestUtils.isEqual(message, mail.getMessage())); assertEquals(1, listener.getSenders().size()); assertEquals(1, listener.getRecipients().size()); assertEquals(1, listener.getStates().size()); assertEquals(1, listener.getMessages().size()); assertEquals(1, listener.getMails().size()); assertEquals("[test@example.com, martijn@djigzo.com]", listener.getRecipients().get(0).toString()); MimeMessage notification = listener.getMessages().get(0); MailUtils.validateMessage(notification); String content = (String) notification.getContent(); assertEquals("property 1 not set\nproperty 2 not set\nnon existing property not set\n", content); }