List of usage examples for javax.mail Message getFrom
public abstract Address[] getFrom() throws MessagingException;
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);/* ww 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:org.elasticsearch.river.email.EmailToJson.java
public static XContentBuilder toJson(Message message, String riverName, EmailRiverConfig config) throws IOException { XContentBuilder out = null;/* ww w. j a v a2 s .c om*/ MimeMessage msg = (MimeMessage) message; try { List<AttachmentInfo> attachments = null; boolean hasAttachment = isContainAttachment(message); if (hasAttachment) { attachments = saveAttachmentToWeedFs(msg, attachments, config); } StringBuffer content = new StringBuffer(30); getMailTextContent(msg, content); int length = 200; String summary = delHTMLTag(content.toString()); summary = (summary.length() > length ? summary.substring(0, length) + "..." : summary); out = jsonBuilder().startObject().field("subject", getSubject(msg)) .field("sent_date", getSentDate(msg, null)) // .field("recv_date", message.getReceivedDate()) .field("from_mail", convertAddress(message.getFrom())) .field("reply_to_mail", convertAddress(message.getReplyTo())).field("from", getFrom(msg)) .field("to", getReceiveAddress(msg, null)).field("content_type", getContentType(msg)) .field("summary", summary).field("content", content.toString()) .field("priority", getPriority(msg)).field("need_receipt", isReplySign(msg)) .field("size", (msg.getSize() / 1024) + "kb").field("contain_attachment", hasAttachment) .field("timestamp", new Date().getTime()).field("via_river", riverName); if (attachments != null && attachments.size() > 0) { XContentBuilder array = out.field("attachments").startArray(); for (int i = 0; i < attachments.size(); i++) { AttachmentInfo info = attachments.get(i); array.startObject().field("file_name", info.fileName).field("file_size", info.fileSize) .field("file_id", info.fileId).field("summary", info.summary).endObject(); } array.endArray(); } } catch (MessagingException e) { logger.error("convert mail to json", e); } assert out != null; return out.endObject(); }
From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java
/** * Send the message using SMTP, if the configuration uses authenticated SMTP, it uses * the user stored in session to get the given login and password. * * @param user// ww w . j a va 2s .co m * @param session * @param message * @throws MessagingException */ protected void sendMessage(User user, Message message) throws MessagingException { cache.sendMessage(message); logger.info("Send message from " + message.getFrom()[0].toString()); }
From source file:FolderModel.java
protected String[] getCachedData(int row) { if (cached[row] == null) { try {//from w ww . j a v a2 s . co m Message m = messages[row]; String[] theData = new String[4]; // Date Date date = m.getSentDate(); if (date == null) { theData[0] = "Unknown"; } else { theData[0] = date.toString(); } // From Address[] adds = m.getFrom(); if (adds != null && adds.length != 0) { theData[1] = adds[0].toString(); } else { theData[1] = ""; } // Subject String subject = m.getSubject(); if (subject != null) { theData[2] = subject; } else { theData[2] = "(No Subject)"; } cached[row] = theData; } catch (MessagingException e) { e.printStackTrace(); } } return cached[row]; }
From source file:org.jahia.modules.gateway.mail.MailToJSONImpl.java
@Handler public void handleExchange(Exchange exchange) { assert exchange.getIn() instanceof MailMessage; long timer = System.currentTimeMillis(); final Message mailMessage = ((MailMessage) exchange.getIn()).getMessage(); try {/*from www. java 2 s. c o m*/ String subject = mailMessage.getSubject(); Address[] from = mailMessage.getFrom(); Address sender = from != null && from.length > 0 ? from[0] : null; if (logger.isDebugEnabled()) { logger.debug("Got message from {} with the subject: {}", sender, subject); } // Parse content and multipart MailContent mailContent = new MailContent(); parseMailMessage(mailMessage, mailContent); if (logger.isTraceEnabled()) { logger.trace("Parsed message body:\n{} \n\nFiles:\n{}", mailContent.getBody(), mailContent.getFiles()); } Pattern matchingPattern = null; MailDecoder decoder = decoders.get("<default>"); // get the default decoder if any decodersLoop: for (MailDecoder examinee : decoders.values()) { List<Pattern> patterns = examinee.getPatterns(); if (patterns != null) { for (Pattern regexp : patterns) { if (matches(mailContent, regexp)) { decoder = examinee; matchingPattern = regexp; break decodersLoop; } } } } if (decoder != null) { if (logger.isDebugEnabled()) { if (matchingPattern == null) { logger.debug("Using default decoder '{}' ({}) for the e-mail", new String[] { decoder.getKey(), decoder.getClass().getName() }); } else { logger.debug("Using decoder '{}' ({}) for the e-mail matching pattern \"{}\"", new String[] { decoder.getKey(), decoder.getClass().getName(), matchingPattern.pattern() }); } } boolean deleteFiles = false; String jsonOutput = null; try { jsonOutput = decoder.decode(matchingPattern, mailContent, mailMessage); } catch (Exception e) { logger.error("Error processing e-mail message with subject \"" + subject + "\" using decoder " + decoder.getKey() + " from " + sender + ", Cause: " + e.getMessage(), e); deleteFiles = true; } if (StringUtils.isNotBlank(jsonOutput)) { if (logger.isTraceEnabled()) { logger.trace("Decoder output is:\n{}", jsonOutput); } DefaultMessage in = new DefaultMessage(); in.setBody(jsonOutput); exchange.setOut(in); } else { deleteFiles = true; } if (deleteFiles && !mailContent.getFiles().isEmpty()) { for (FileItem file : mailContent.getFiles()) { FileUtils.deleteQuietly(file.getFile()); } } } else { if (logger.isDebugEnabled()) { logger.debug("Skipping e-mail as no decoder configured to match subject: {}\n", subject); } } if (logger.isDebugEnabled()) { logger.debug("Message from {} with the subject '{}' processed in {} ms", new Object[] { sender, subject, System.currentTimeMillis() - timer }); } } catch (Exception e) { logger.error(e.getMessage(), e); } }
From source file:org.accesointeligente.server.robots.ResponseChecker.java
public void connectAndCheck() { if (ApplicationProperties.getProperty("email.server") == null || ApplicationProperties.getProperty("email.user") == null || ApplicationProperties.getProperty("email.password") == null || ApplicationProperties.getProperty("email.folder") == null || ApplicationProperties.getProperty("email.failfolder") == null || ApplicationProperties.getProperty("attachment.directory") == null || ApplicationProperties.getProperty("attachment.baseurl") == null) { logger.error("Properties are not defined!"); return;// w w w . j a v a2s . c om } org.hibernate.Session hibernate = null; try { session = Session.getInstance(props, null); store = session.getStore("imaps"); store.connect(ApplicationProperties.getProperty("email.server"), ApplicationProperties.getProperty("email.user"), ApplicationProperties.getProperty("email.password")); Folder failbox = store.getFolder(ApplicationProperties.getProperty("email.failfolder")); Folder inbox = store.getFolder(ApplicationProperties.getProperty("email.folder")); inbox.open(Folder.READ_WRITE); for (Message message : inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false))) { try { logger.info("Sender: " + message.getFrom()[0] + "\tSubject: " + message.getSubject()); remoteIdentifiers = null; messageBody = null; remoteIdentifiers = new HashSet<String>(); if (message.getSubject() != null) { Matcher matcher = pattern.matcher(message.getSubject()); if (matcher.matches()) { remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); } } Object content = message.getContent(); if (content instanceof Multipart) { Multipart mp = (Multipart) message.getContent(); logger.info("Email content type is Multipart, each part of " + mp.getCount() + " will be processed"); for (int i = 0, n = mp.getCount(); i < n; i++) { Part part = mp.getBodyPart(i); logger.info("Part: " + (i + 1) + " of " + mp.getCount()); processPart(part); } } else if (content instanceof String) { logger.info("Email content type is String"); messageBody = (String) content; Matcher matcher; StringTokenizer tokenizer = new StringTokenizer(messageBody); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); matcher = pattern.matcher(token); if (matcher.matches()) { remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); } } } else { logger.info("Email content type isn't String or Multipart"); message.setFlag(Flag.SEEN, false); inbox.copyMessages(new Message[] { message }, failbox); message.setFlag(Flag.DELETED, true); inbox.expunge(); continue; } Boolean requestFound = false; Matcher matcher = htmlPattern.matcher(messageBody); if (matcher.find()) { messageBody = htmlToString(messageBody); } logger.info("Searching for Request Remote Identifier"); for (String remoteIdentifier : remoteIdentifiers) { hibernate = HibernateUtil.getSession(); hibernate.beginTransaction(); Criteria criteria = hibernate.createCriteria(Request.class); criteria.add(Restrictions.eq("remoteIdentifier", remoteIdentifier)); Request request = (Request) criteria.uniqueResult(); hibernate.getTransaction().commit(); if (request != null) { logger.info("Request found for Remote Identifier: " + remoteIdentifier); Response response; // If the attachments haven't been used, use them. Otherwise, copy them. if (!requestFound) { response = createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); } else { response = createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); } hibernate = HibernateUtil.getSession(); hibernate.beginTransaction(); response.setRequest(request); request.setStatus(RequestStatus.RESPONDED); request.setExpired(RequestExpireType.WITHRESPONSE); request.setResponseDate(new Date()); hibernate.update(request); hibernate.update(response); hibernate.getTransaction().commit(); requestFound = true; } } if (!requestFound) { logger.info("Request not found"); createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); message.setFlag(Flag.SEEN, false); inbox.copyMessages(new Message[] { message }, failbox); message.setFlag(Flag.DELETED, true); inbox.expunge(); } } catch (Exception e) { if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) { hibernate.getTransaction().rollback(); } logger.error(e.getMessage(), e); } } } catch (Exception e) { if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) { hibernate.getTransaction().rollback(); } logger.error(e.getMessage(), e); } }
From source file:com.opinionlab.woa.Awesome.java
public Awesome(Message message) { try {/*from w ww.j a v a2s. co m*/ this.messageID = ((MimeMessage) message).getMessageID(); this.id = ID_PTN.matcher(this.messageID).replaceAll("_"); this.receivedDate = message.getReceivedDate(); this.monthDay = DATE_FORMATTER .format(LocalDateTime.ofInstant(receivedDate.toInstant(), systemDefault())); this.to = new Person((InternetAddress) //todo Do this smarter message.getRecipients(Message.RecipientType.TO)[0]); this.from = new Person((InternetAddress) message.getFrom()[0]); this.subject = message.getSubject(); final MimeMessageParser parser = new MimeMessageParser((MimeMessage) message).parse(); if (!parser.hasPlainContent()) { LOGGER.error(format("Unable to parse message '%s'; has no plain content", this.messageID)); this.comment = "Unknown content."; } else { this.comment = parseContent(parser.getPlainContent()); } } catch (Throwable t) { throw new IllegalArgumentException(t); } }
From source file:com.cubusmail.server.mail.util.MessageComparator.java
public int compare(Message msg1, Message msg2) { int result = 0; if (msg1.isExpunged() || msg2.isExpunged()) { return result; }/*w ww .j ava 2 s . co m*/ try { if (MessageListFields.SUBJECT == this.field) { if (msg1.getSubject() != null && msg2.getSubject() != null) { result = msg1.getSubject().compareToIgnoreCase(msg2.getSubject()); } else { result = -1; } } else if (MessageListFields.FROM == this.field) { String fromString1 = MessageUtils.getMailAdressString(msg1.getFrom(), AddressStringType.PERSONAL); String fromString2 = MessageUtils.getMailAdressString(msg2.getFrom(), AddressStringType.PERSONAL); if (fromString1 != null && fromString2 != null) { result = fromString1.compareToIgnoreCase(fromString2); } else { result = -1; } } else if (MessageListFields.SEND_DATE == this.field) { Date date1 = msg1.getSentDate(); Date date2 = msg2.getSentDate(); if (date1 != null && date2 != null) { result = date1.compareTo(date2); } else { result = -1; } } else if (MessageListFields.SIZE == this.field) { int size1 = msg1.getSize(); int size2 = msg2.getSize(); result = Integer.valueOf(size1).compareTo(Integer.valueOf(size2)); } } catch (MessagingException e) { log.warn(e.getMessage(), e); } if (!this.ascending) { result = result * (-1); } 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 />/* w w w. j ava 2s .c om*/ * * 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:org.nuxeo.cm.mail.actionpipe.ExtractMessageInformation.java
@Override @SuppressWarnings("deprecation") public boolean execute(ExecutionContext context) throws MessagingException { File tmpOutput = null;//from w w w.j ava 2s . c om OutputStream out = null; try { Message originalMessage = context.getMessage(); if (log.isDebugEnabled()) { log.debug("Transforming message, original subject: " + originalMessage.getSubject()); } // fully load the message before trying to parse to // override most of server bugs, see // http://java.sun.com/products/javamail/FAQ.html#imapserverbug Message message; if (originalMessage instanceof MimeMessage) { message = new MimeMessage((MimeMessage) originalMessage); if (log.isDebugEnabled()) { log.debug("Transforming message after full load: " + message.getSubject()); } } else { // stuck with the original one message = originalMessage; } Address[] from = message.getFrom(); if (from != null) { Address addr = from[0]; if (addr instanceof InternetAddress) { InternetAddress iAddr = (InternetAddress) addr; context.put(SENDER_KEY, iAddr.getPersonal()); context.put(SENDER_EMAIL_KEY, iAddr.getAddress()); } else { context.put(SENDER_KEY, addr.toString()); } } Date receivedDate = message.getReceivedDate(); if (receivedDate == null) { // try to get header manually String[] dateHeader = message.getHeader("Date"); if (dateHeader != null) { try { long time = Date.parse(dateHeader[0]); receivedDate = new Date(time); } catch (IllegalArgumentException e) { // nevermind } } } if (receivedDate != null) { Calendar date = Calendar.getInstance(); date.setTime(receivedDate); context.put(RECEPTION_DATE_KEY, date); } String subject = message.getSubject(); if (subject != null) { subject = subject.trim(); } if (subject == null || "".equals(subject)) { subject = "<Unknown>"; } context.put(SUBJECT_KEY, subject); String[] messageIdHeader = message.getHeader("Message-ID"); if (messageIdHeader != null) { context.put(MESSAGE_ID_KEY, messageIdHeader[0]); } // TODO: pass it through initial context MimetypeRegistry mimeService = (MimetypeRegistry) context.getInitialContext().get(MIMETYPE_SERVICE_KEY); if (mimeService == null) { log.error("Could not retrieve mimetype service"); } // add all content as first blob tmpOutput = File.createTempFile("injectedEmail", ".eml"); Framework.trackFile(tmpOutput, tmpOutput); out = new FileOutputStream(tmpOutput); message.writeTo(out); Blob blob = Blobs.createBlob(tmpOutput, MESSAGE_RFC822_MIMETYPE, null, subject + ".eml"); List<Blob> blobs = new ArrayList<>(); blobs.add(blob); context.put(ATTACHMENTS_KEY, blobs); // process content getAttachmentParts(message, subject, mimeService, context); return true; } catch (IOException e) { log.error(e); } finally { IOUtils.closeQuietly(out); } return false; }