List of usage examples for javax.mail Message getSubject
public abstract String getSubject() throws MessagingException;
From source file:org.b3log.solo.mail.local.MailSender.java
/** * Converts the specified message into a {@link javax.mail.Message * javax.mail.Message}./* w ww . j a v a2s. c o m*/ * * @param message the specified message * @return a {@link javax.mail.internet.MimeMessage} * @throws Exception if converts error */ public javax.mail.Message convert2JavaMailMsg(final Message message) throws Exception { if (null == message) { return null; } if (StringUtils.isBlank(message.getFrom())) { throw new MessagingException("Null from"); } if (null == message.getRecipients() || message.getRecipients().isEmpty()) { throw new MessagingException("Null recipients"); } final MimeMessage ret = new MimeMessage(getSession()); ret.setFrom(new InternetAddress(message.getFrom())); final String subject = message.getSubject(); ret.setSubject(MimeUtility.encodeText(subject != null ? subject : "", "UTF-8", "B")); final String htmlBody = message.getHtmlBody(); ret.setContent(htmlBody != null ? htmlBody : "", "text/html;charset=UTF-8"); ret.addRecipients(RecipientType.TO, transformRecipients(message.getRecipients())); return ret; }
From source file:org.apache.usergrid.rest.management.users.MUUserResourceIT.java
@Test public void testUnconfirmedAdminLogin() throws Exception { // Setup properties to require confirmation of users // ------------------------------------------- Map<String, String> originalProperties = getRemoteTestProperties(); try {//from w w w. java2s.c om setTestProperty(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS, "false"); setTestProperty(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS, "false"); setTestProperty(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION, "true"); setTestProperty(PROPERTIES_SYSADMIN_EMAIL, "sysadmin-1@mockserver.com"); setTestProperty(PROPERTIES_NOTIFY_ADMIN_OF_ACTIVATION, "true"); assertTrue(setup.getMgmtSvc().newAdminUsersRequireConfirmation()); assertFalse(setup.getMgmtSvc().newAdminUsersNeedSysAdminApproval()); // Setup org/app/user variables and create them // ------------------------------------------- String orgName = this.getClass().getName(); String appName = "testUnconfirmedAdminLogin"; String userName = "TestUser"; String email = "test-user-46@mockserver.com"; String passwd = "testpassword"; OrganizationOwnerInfo orgOwner; orgOwner = setup.getMgmtSvc().createOwnerAndOrganization(orgName, userName, appName, email, passwd, false, false); assertNotNull(orgOwner); String returnedUsername = orgOwner.getOwner().getUsername(); assertEquals(userName, returnedUsername); UserInfo adminUserInfo = setup.getMgmtSvc().getAdminUserByUsername(userName); assertNotNull(adminUserInfo); assertFalse("adminUser should not be activated yet", adminUserInfo.isActivated()); assertFalse("adminUser should not be confirmed yet", adminUserInfo.isConfirmed()); // Attempt to authenticate but this should fail // ------------------------------------------- JsonNode node; try { node = resource().path("/management/token").queryParam("grant_type", "password") .queryParam("username", userName).queryParam("password", passwd) .accept(MediaType.APPLICATION_JSON).get(JsonNode.class); fail("Unconfirmed users should not be authorized to authenticate."); } catch (UniformInterfaceException e) { node = e.getResponse().getEntity(JsonNode.class); assertEquals("invalid_grant", node.get("error").getTextValue()); assertEquals("User must be confirmed to authenticate", node.get("error_description").getTextValue()); LOG.info("Unconfirmed user was not authorized to authenticate!"); } // Confirm the getting account confirmation email for unconfirmed user // ------------------------------------------- List<Message> inbox = Mailbox.get(email); assertFalse(inbox.isEmpty()); MockImapClient client = new MockImapClient("mockserver.com", "test-user-46", "somepassword"); client.processMail(); Message confirmation = inbox.get(0); assertEquals("User Account Confirmation: " + email, confirmation.getSubject()); // Extract the token to confirm the user // ------------------------------------------- String token = getTokenFromMessage(confirmation); LOG.info(token); ActivationState state = setup.getMgmtSvc() .handleConfirmationTokenForAdminUser(orgOwner.getOwner().getUuid(), token); assertEquals(ActivationState.ACTIVATED, state); Message activation = inbox.get(1); assertEquals("User Account Activated", activation.getSubject()); client = new MockImapClient("mockserver.com", "test-user-46", "somepassword"); client.processMail(); // Attempt to authenticate again but this time should pass // ------------------------------------------- node = resource().path("/management/token").queryParam("grant_type", "password") .queryParam("username", userName).queryParam("password", passwd) .accept(MediaType.APPLICATION_JSON).get(JsonNode.class); assertNotNull(node); LOG.info("Authentication succeeded after confirmation: {}.", node.toString()); } finally { setTestProperties(originalProperties); } }
From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java
/** * Returns new messages and fetches details for each message. *///from ww w . ja v a2 s .co m @Transactional(readOnly = false) public ResultClass<Boolean> downloadEmails() { ResultClass<Boolean> result = new ResultClass<>(); Properties properties = getServerProperties(protocol, host, port); Session session = Session.getDefaultInstance(properties); try { // connects to the message store Store store = session.getStore(protocol); store.connect(userName, password); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_ONLY); // fetches new messages from server Message[] messages = folderInbox.getMessages(); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; String[] idHeaders = msg.getHeader("MESSAGE-ID"); if (idHeaders != null && idHeaders.length > 0) { MessageBox exists = repositoryMailBox.getMessageBox(idHeaders[0]); if (exists == null) { MessageBox messageBox = new MessageBox(); messageBox.setSubject(msg.getSubject()); messageBox.setCode(idHeaders[0]); Address[] fromAddresses = msg.getFrom(); String from = InternetAddress.toString(fromAddresses); if (from.startsWith("=?")) { from = MimeUtility.decodeWord(from); } messageBox.setFrom(from); String to = InternetAddress.toString(msg.getRecipients(RecipientType.TO)); if (to.startsWith("=?")) { to = MimeUtility.decodeWord(to); } messageBox.setTo(to); String[] replyHeaders = msg.getHeader("References"); if (replyHeaders != null && replyHeaders.length > 0) { StringTokenizer tokens = new StringTokenizer(replyHeaders[0]); MessageBox parent = repositoryMailBox.getMessageBox(tokens.nextToken()); if (parent != null) parent.addReply(messageBox); } result = parseSubjectAndCreate(messageBox, msg); } } } folderInbox.close(false); store.close(); return result; } catch (NoSuchProviderException ex) { logger.error("No provider for protocol: " + protocol); ex.printStackTrace(); } catch (MessagingException ex) { logger.error("Could not connect to the message store"); ex.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } result.setSingleElement(false); return result; }
From source file:org.openadaptor.auxil.connector.mail.MailReadConnector.java
/** * Retrieves any "new" (ie. any eligible to be processed) messages from the InBox. We * only process the first message in the folder. The rest will be picked up on * subsequent polls. If required we also try to set the message status as READ/SEEN. * <p />// www . j a v a2 s. c o m * * If the message is deleted while we are processing it then we just log the problem * and return null. * * @return the first mail message to precess or null if none present. * * @throws MessagingException if the inbox can not be opened, if there was a comms * error or if we failed to retrieve the message details. */ private Message getNextMessage() throws MessagingException { if (inbox == null || !inbox.isOpen()) openInbox(); Message[] messages = inbox.getMessages(); log.debug(messages.length + " msssage(s) found"); if (messages.length == 0) return null; int index = 0; try { while (index < messages.length) { // we only process the first unread message in the folder. The rest will be // picked up on subsequent polls Message msg = messages[index++]; if (isToBeProcessed(msg)) { log.info("Processing message [" + msg.getSubject() + "] from " + msg.getFrom()[0]); return msg; } } } catch (NullPointerException e) { // ok, so this is a little dodgy as different version of the JavaMail API might // exhibit different behaviour but works for 1.3 and 1.4 log.warn("Message [" + index + "] deleted by external party. " + "Will skip this iteration and continue on the next poll."); } catch (Exception e) { log.warn("Failed to retrieve message [" + index + "]: " + e.getMessage() + ". " + "Will skip this iteration and continue on the next poll."); } return null; }
From source file:gov.nih.nci.firebird.service.messages.email.EmailServiceImplTest.java
private String doSendMessageTest(List<String> cc) throws MessagingException, IOException { String overrideEmail = "overrideEmail@example.com"; mailbox = Mailbox.get(overrideEmail); bean.setOverrideEmailAddress(overrideEmail); bean.sendMessage(TEST_TO_ADDRESS, cc, null, testMessage); Message message = mailbox.get(0); InternetAddress fromAddress = (InternetAddress) message.getFrom()[0]; assertEquals(TEST_FROM_ADDRESS, fromAddress.getAddress()); assertEquals(TEST_FROM_NAME, fromAddress.getPersonal()); InternetAddress toAddress = (InternetAddress) message.getRecipients(RecipientType.TO)[0]; assertEquals(overrideEmail, toAddress.getAddress()); assertNull(message.getRecipients(RecipientType.CC)); assertEquals(TEST_SUBJECT, message.getSubject()); assertTrue(message.getContent().toString().contains(TEST_CONTENT)); assertTrue(message.getContent().toString().contains(EmailServiceImpl.TO_OVERRIDE_HEADING)); assertTrue(message.getContent().toString().contains(TEST_TO_ADDRESS)); assertTrue(message.getContent().toString().contains(EmailServiceImpl.LINE_SEPARATOR)); return message.getContent().toString(); }
From source file:com.crawlersick.nettool.GetattchmentFromMail1.java
public boolean fetchmailforattch() throws IOException, MessagingException { boolean fetchtest = false; Properties props = new Properties(); props.setProperty("mail.store.protocol", "imaps"); try {// w w w. ja v a 2 s .c o m Session session = Session.getInstance(props, null); Store store = session.getStore(); store.connect(IMapHost, MailId, MailPassword); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); totalmailcount = inbox.getMessageCount(); Message msg = null; for (int i = totalmailcount; i > 0; i--) { fromadd = ""; msg = inbox.getMessage(i); Address[] in = msg.getFrom(); for (Address address : in) { fromadd = address.toString() + fromadd; //System.out.println("FROM:" + address.toString()); } if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches( "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice")) break; } if (fromadd.equals("'")) { log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId); return fetchtest; } // Multipart mp = (Multipart) msg.getContent(); // BodyPart bp = mp.getBodyPart(0); sentdate = msg.getSentDate().toString(); subject = msg.getSubject(); Content = msg.getContent().toString(); log.log(Level.INFO, Content); log.log(Level.INFO, sentdate); localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data..."); LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent); Multipart multipart = (Multipart) msg.getContent(); for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) { continue; // dealing with attachments only } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); InputStream is = bodyPart.getInputStream(); //validvgbinary = IOUtils.toByteArray(is); int nRead; byte[] data = new byte[5000000]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); validvgbinary = buffer.toByteArray(); break; } fetchtest = true; } catch (Exception mex) { mex.printStackTrace(); } return fetchtest; }
From source file:org.springframework.integration.mail.transformer.AbstractMailMessageTransformer.java
private Map<String, Object> extractHeaderMapFromMailMessage(javax.mail.Message mailMessage) { try {//from w w w .j ava 2 s . co m Map<String, Object> headers = new HashMap<String, Object>(); headers.put(MailHeaders.FROM, this.convertToString(mailMessage.getFrom())); headers.put(MailHeaders.BCC, this.convertToStringArray(mailMessage.getRecipients(RecipientType.BCC))); headers.put(MailHeaders.CC, this.convertToStringArray(mailMessage.getRecipients(RecipientType.CC))); headers.put(MailHeaders.TO, this.convertToStringArray(mailMessage.getRecipients(RecipientType.TO))); headers.put(MailHeaders.REPLY_TO, this.convertToString(mailMessage.getReplyTo())); headers.put(MailHeaders.SUBJECT, mailMessage.getSubject()); return headers; } catch (Exception e) { throw new MessagingException("conversion of MailMessage headers failed", e); } }
From source file:de.mmichaelis.maven.mojo.MailDevelopersMojoTest.java
@Test public void testFullyConfiguredMail() throws Exception { final MavenProject project = mock(MavenProject.class); when(project.getDevelopers()).thenReturn(Arrays.asList(developers)); mojoWrapper.setProject(project);//from w w w . ja v a 2 s . c o m mojoWrapper.setCharset("UTF-8"); mojoWrapper.setExpires("2"); final String from = "John Doe <johndoe@github.com>"; mojoWrapper.setFrom(from); mojoWrapper.setPriority("high"); final String subject = "testFullyConfiguredMail"; mojoWrapper.setSubject(subject); final String topic = "MyTopic"; mojoWrapper.setTopic(topic); final Date now = new Date(); mojoWrapper.execute(); final Mailbox inbox = Mailbox.get(developers[0].getEmail()); assertEquals("One new email for the first developer.", 1, inbox.size()); final Message message = inbox.get(0); assertTrue("Sent date should signal to be today.", DateUtils.isSameDay(now, message.getSentDate())); assertEquals("Size of recipients should match number of developers.", developers.length, message.getAllRecipients().length); final Address[] senders = message.getFrom(); assertNotNull("Sender address should be set.", senders); assertEquals("Number of senders should be 1.", 1, senders.length); assertEquals("Sender in message should match original sender.", from, senders[0].toString()); final String messageSubject = message.getSubject(); assertTrue("Subject should contain original subject.", messageSubject.contains(subject)); assertTrue("Subject should contain topic.", messageSubject.contains(topic)); // TODO: Check additional headers }
From source file:mx.uaq.facturacion.enlace.EmailParserUtils.java
/** * Parses any {@link Multipart} instances that contain text or Html attachments, * {@link InputStream} instances, additional instances of {@link Multipart} * or other attached instances of {@link javax.mail.Message}. * * Will create the respective {@link EmailFragment}s representing those attachments. * * Instances of {@link javax.mail.Message} are delegated to * {@link #handleMessage(File, javax.mail.Message, List)}. Further instances * of {@link Multipart} are delegated to * {@link #handleMultipart(File, Multipart, javax.mail.Message, List)}. * * @param directory Must not be null/*ww w. jav a 2 s .c om*/ * @param multipart Must not be null * @param mailMessage Must not be null * @param emailFragments Must not be null */ public static void handleMultipart(File directory, Multipart multipart, javax.mail.Message mailMessage, List<EmailFragment> emailFragments) { Assert.notNull(directory, "The directory must not be null."); Assert.notNull(multipart, "The multipart object to be parsed must not be null."); Assert.notNull(mailMessage, "The mail message to be parsed must not be null."); Assert.notNull(emailFragments, "The collection of emailfragments must not be null."); final int count; try { count = multipart.getCount(); if (LOGGER.isInfoEnabled()) { LOGGER.info(String.format("Number of enclosed BodyPart objects: %s.", count)); } } catch (MessagingException e) { throw new IllegalStateException("Error while retrieving the number of enclosed BodyPart objects.", e); } for (int i = 0; i < count; i++) { final BodyPart bp; try { bp = multipart.getBodyPart(i); } catch (MessagingException e) { throw new IllegalStateException("Error while retrieving body part.", e); } final String contentType; String filename; final String disposition; final String subject; try { contentType = bp.getContentType(); filename = bp.getFileName(); disposition = bp.getDisposition(); subject = mailMessage.getSubject(); if (filename == null && bp instanceof MimeBodyPart) { filename = ((MimeBodyPart) bp).getContentID(); } } catch (MessagingException e) { throw new IllegalStateException("Unable to retrieve body part meta data.", e); } if (LOGGER.isInfoEnabled()) { LOGGER.info(String.format( "BodyPart - Content Type: '%s', filename: '%s', disposition: '%s', subject: '%s'", new Object[] { contentType, filename, disposition, subject })); } if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) { LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType)); } final Object content; try { content = bp.getContent(); } catch (IOException e) { throw new IllegalStateException("Error while retrieving the email contents.", e); } catch (MessagingException e) { throw new IllegalStateException("Error while retrieving the email contents.", e); } if (content instanceof String) { if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) { emailFragments.add(new EmailFragment(directory, i + "-" + filename, content)); LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType)); } else { final String textFilename; final ContentType ct; try { ct = new ContentType(contentType); } catch (ParseException e) { throw new IllegalStateException("Error while parsing content type '" + contentType + "'.", e); } if ("text/plain".equalsIgnoreCase(ct.getBaseType())) { textFilename = "message.txt"; } else if ("text/html".equalsIgnoreCase(ct.getBaseType())) { textFilename = "message.html"; } else { textFilename = "message.other"; } emailFragments.add(new EmailFragment(directory, textFilename, content)); } } else if (content instanceof InputStream) { final InputStream inputStream = (InputStream) content; final ByteArrayOutputStream bis = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, bis); } catch (IOException e) { throw new IllegalStateException( "Error while copying input stream to the ByteArrayOutputStream.", e); } emailFragments.add(new EmailFragment(directory, filename, bis.toByteArray())); } else if (content instanceof javax.mail.Message) { handleMessage(directory, (javax.mail.Message) content, emailFragments); } else if (content instanceof Multipart) { final Multipart mp2 = (Multipart) content; handleMultipart(directory, mp2, mailMessage, emailFragments); } else { throw new IllegalStateException("Content type not handled: " + content.getClass().getSimpleName()); } } }
From source file:org.mule.transport.email.MailMuleMessageFactory.java
@Override protected void addProperties(DefaultMuleMessage muleMessage, Object transportMessage) throws Exception { super.addProperties(muleMessage, transportMessage); Message mailMessage = (Message) transportMessage; addRecipientProperty(muleMessage, mailMessage, RecipientType.TO, MailProperties.TO_ADDRESSES_PROPERTY); addRecipientProperty(muleMessage, mailMessage, RecipientType.CC, MailProperties.CC_ADDRESSES_PROPERTY); addRecipientProperty(muleMessage, mailMessage, RecipientType.BCC, MailProperties.BCC_ADDRESSES_PROPERTY); addReplyToProperty(muleMessage, mailMessage); addFromProperty(muleMessage, mailMessage); muleMessage.setInboundProperty(MailProperties.SUBJECT_PROPERTY, StringUtils.defaultIfEmpty(mailMessage.getSubject(), "(no subject)")); muleMessage.setInboundProperty(MailProperties.CONTENT_TYPE_PROPERTY, StringUtils.defaultIfEmpty(mailMessage.getContentType(), "text/plain")); addSentDateProperty(muleMessage, mailMessage); addMailHeadersToMessageProperties(mailMessage, muleMessage); }