List of usage examples for javax.mail.internet MimeMessage getSubject
@Override public String getSubject() throws MessagingException
From source file:org.apache.james.transport.mailets.HeadersToHTTP.java
private HashSet<NameValuePair> getNameValuePairs(MimeMessage message) throws UnsupportedEncodingException, MessagingException { // to_address // from//from w w w . j a va2 s . com // reply to // subject HashSet<NameValuePair> pairs = new HashSet<NameValuePair>(); if (message != null) { if (message.getSender() != null) { pairs.add(new BasicNameValuePair("from", message.getSender().toString())); } if (message.getReplyTo() != null) { pairs.add(new BasicNameValuePair("reply_to", Arrays.toString(message.getReplyTo()))); } if (message.getMessageID() != null) { pairs.add(new BasicNameValuePair("message_id", message.getMessageID())); } if (message.getSubject() != null) { pairs.add(new BasicNameValuePair("subject", message.getSubject())); } pairs.add(new BasicNameValuePair("size", Integer.toString(message.getSize()))); } pairs.add(new BasicNameValuePair(parameterKey, parameterValue)); return pairs; }
From source file:com.adaptris.mail.MailReceiverCase.java
protected void printMessageInfo(MimeMessage msg) throws Exception { MessageParser mp = new MessageParser(msg); logger.debug("Got Message :- " + msg.getSubject()); logger.trace("With ID: " + mp.getMessageId()); Enumeration e = msg.getAllHeaders(); while (e.hasMoreElements()) { Header h = (Header) e.nextElement(); logger.trace("HeaderLine " + h.getName() + ": " + h.getValue()); }//from ww w . j av a2s .c om if (mp.hasAttachments()) { while (mp.hasMoreAttachments()) { Attachment a = mp.nextAttachment(); logger.trace("Contains Attachment : " + a); } } }
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();//from ww w . j a va2 s . c o m 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:org.openhie.openempi.service.MailEngineTest.java
public void testSendMessageWithAttachment() throws Exception { final String ATTACHMENT_NAME = "boring-attachment.txt"; //mock smtp server Wiser wiser = new Wiser(); int port = 2525 + (int) (Math.random() * 100); mailSender.setPort(port);//w w w.ja v a 2 s . c om wiser.setPort(port); wiser.start(); Date dte = new Date(); String emailSubject = "grepster testSendMessageWithAttachment: " + dte; String emailBody = "Body of the grepster testSendMessageWithAttachment message sent at: " + dte; ClassPathResource cpResource = new ClassPathResource("/test-attachment.txt"); mailEngine.sendMessage(new String[] { "foo@bar.com" }, mailMessage.getFrom(), cpResource, emailBody, emailSubject, ATTACHMENT_NAME); wiser.stop(); assertTrue(wiser.getMessages().size() == 1); WiserMessage wm = wiser.getMessages().get(0); MimeMessage mm = wm.getMimeMessage(); Object o = wm.getMimeMessage().getContent(); assertTrue(o instanceof MimeMultipart); MimeMultipart multi = (MimeMultipart) o; int numOfParts = multi.getCount(); boolean hasTheAttachment = false; for (int i = 0; i < numOfParts; i++) { BodyPart bp = multi.getBodyPart(i); String disp = bp.getDisposition(); if (disp == null) { //the body of the email Object innerContent = bp.getContent(); MimeMultipart innerMulti = (MimeMultipart) innerContent; assertEquals(emailBody, innerMulti.getBodyPart(0).getContent()); } else if (disp.equals(Part.ATTACHMENT)) { //the attachment to the email hasTheAttachment = true; assertEquals(ATTACHMENT_NAME, bp.getFileName()); } else { fail("Did not expect to be able to get here."); } } assertTrue(hasTheAttachment); assertEquals(emailSubject, mm.getSubject()); }
From source file:org.openmrs.contrib.metadatarepository.service.MailEngineTest.java
@Test public void testSendMessageWithAttachment() throws Exception { final String ATTACHMENT_NAME = "boring-attachment.txt"; //mock smtp server Wiser wiser = new Wiser(); int port = 2525 + (int) (Math.random() * 100); mailSender.setPort(port);/*ww w . jav a2 s . c o m*/ wiser.setPort(port); wiser.start(); Date dte = new Date(); String emailSubject = "grepster testSendMessageWithAttachment: " + dte; String emailBody = "Body of the grepster testSendMessageWithAttachment message sent at: " + dte; ClassPathResource cpResource = new ClassPathResource("/test-attachment.txt"); // a null from should work mailEngine.sendMessage(new String[] { "foo@bar.com" }, null, cpResource, emailBody, emailSubject, ATTACHMENT_NAME); mailEngine.sendMessage(new String[] { "foo@bar.com" }, mailMessage.getFrom(), cpResource, emailBody, emailSubject, ATTACHMENT_NAME); wiser.stop(); // one without and one with from assertTrue(wiser.getMessages().size() == 2); WiserMessage wm = wiser.getMessages().get(0); MimeMessage mm = wm.getMimeMessage(); Object o = wm.getMimeMessage().getContent(); assertTrue(o instanceof MimeMultipart); MimeMultipart multi = (MimeMultipart) o; int numOfParts = multi.getCount(); boolean hasTheAttachment = false; for (int i = 0; i < numOfParts; i++) { BodyPart bp = multi.getBodyPart(i); String disp = bp.getDisposition(); if (disp == null) { //the body of the email Object innerContent = bp.getContent(); MimeMultipart innerMulti = (MimeMultipart) innerContent; assertEquals(emailBody, innerMulti.getBodyPart(0).getContent()); } else if (disp.equals(Part.ATTACHMENT)) { //the attachment to the email hasTheAttachment = true; assertEquals(ATTACHMENT_NAME, bp.getFileName()); } else { fail("Did not expect to be able to get here."); } } assertTrue(hasTheAttachment); assertEquals(emailSubject, mm.getSubject()); }
From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java
/** * Process an email, extracting attachments and constructing a Message. * * @param mail the email to be processed. * @param mailingList the mailing list it is going to be affected to. * @param event the event which will be send at the end of all processing. * @throws MessagingException/*from w w w . j a va 2 s . c o m*/ * @throws IOException */ public void prepareMessage(MimeMessage mail, MessageListener mailingList, MessageEvent event) throws MessagingException, IOException { String sender = ((InternetAddress[]) mail.getFrom())[0].getAddress(); if (!mailingList.checkSender(sender)) { return; } Message message = new Message(); message.setComponentId(mailingList.getComponentId()); message.setSender(sender); message.setSentDate(mail.getSentDate()); message.setMessageId(mail.getMessageID()); String[] referenceId = mail.getHeader(MAIL_HEADER_IN_REPLY_TO); if (referenceId == null || referenceId.length == 0) { referenceId = mail.getHeader(MAIL_HEADER_REFERENCES); } if (referenceId == null || referenceId.length == 0) { message.setReferenceId(null); } else { message.setReferenceId(referenceId[0]); } message.setTitle(mail.getSubject()); SilverTrace.info("mailingList", "MailProcessor.prepareMessage()", "mailinglist.notification.error", "Processing message " + mail.getSubject()); Object content = mail.getContent(); if (content instanceof Multipart) { processMultipart((Multipart) content, message); } else if (content instanceof String) { processBody((String) content, mail.getContentType(), message); } event.addMessage(message); }
From source file:io.lavagna.service.MailTicketService.java
public void checkNew() { List<ProjectMailTicketConfig> entries = mailTicketRepository.findAll(); for (ProjectMailTicketConfig entry : entries) { if (entry.getEntries().size() == 0 || !entry.getEnabled()) { continue; }/* w ww. j a va2s .c o m*/ MailReceiver receiver = entry.getConfig().getInboundProtocol().startsWith("pop3") ? getPop3MailReceiver(entry.getConfig()) : getImapMailReceiver(entry.getConfig()); try { Date updateLastChecked = entry.getLastChecked(); Object[] messages = receiver.receive(); LOG.debug("found {} messages", messages.length); for (int i = 0; i < messages.length; i++) { MimeMessage message = (MimeMessage) messages[i]; if (!message.getReceivedDate().after(entry.getLastChecked())) { continue; } else { updateLastChecked = message.getReceivedDate().after(updateLastChecked) ? message.getReceivedDate() : updateLastChecked; } String deliveredTo = getDeliveredTo(message); for (ProjectMailTicket ticketConfig : entry.getEntries()) { if (ticketConfig.getEnabled() && ticketConfig.getAlias().equals(deliveredTo)) { String from = getFrom(message); String name = getName(message); Matcher m = CARD_SHORT_NAME.matcher(message.getSubject()); if (!m.find() || (m.find() && !cardService.existCardWith(m.group("shortname"), Integer.parseInt(m.group("sequence"))))) { try { ImmutablePair<Card, User> cardAndUser = createCard(message.getSubject(), getTextFromMessage(message), from, ticketConfig.getColumnId()); notify(cardAndUser.getLeft(), entry, ticketConfig, cardAndUser.getRight(), from, name); } catch (IOException | MessagingException e) { LOG.error("failed to parse message body", e); } } } } } mailTicketRepository.updateLastChecked(entry.getId(), updateLastChecked); } catch (MessagingException e) { LOG.error("could not retrieve messages for ticket mail config id: {}", entry.getId()); } } }
From source file:edu.stanford.muse.util.EmailUtils.java
/** * best effort to toString something about the given message. * use only for diagnostics, not for user-visible messages. * treads defensively, this can be called to report on a badly formatted message. */// w w w .j av a 2s .c om public static String formatMessageHeader(MimeMessage m) throws MessagingException { StringBuilder sb = new StringBuilder(); sb.append("To: "); if (m == null) { log.warn("Trying to format null message!?"); return "Null message"; } try { Address[] tos = m.getAllRecipients(); if (tos != null) for (Address a : tos) sb.append(a.toString() + " "); sb.append("\n"); } catch (Exception e) { Util.print_exception(e, log); } sb.append("From: "); try { Address[] froms = m.getFrom(); if (froms != null) for (Address a : froms) sb.append(a.toString() + " "); sb.append("\n"); } catch (Exception e) { Util.print_exception(e, log); } try { sb.append("Subject: " + m.getSubject()); sb.append("Message-ID: " + m.getMessageID()); } catch (Exception e) { Util.print_exception(e, log); } return sb.toString(); }
From source file:com.formkiq.web.WorkflowAddControllerIntegrationTest.java
/** * verify email is sent for signing./* w w w . j a v a 2s . co m*/ * @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:com.formkiq.web.WorkflowAddControllerIntegrationTest.java
/** * Verify Completion Email./*from w ww. j a va 2 s. c om*/ * @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(); }