List of usage examples for javax.mail Message getAllHeaders
public Enumeration<Header> getAllHeaders() throws MessagingException;
From source file:net.orpiske.dcd.collector.dataset.impl.MBoxDataSet.java
@Override public Data next() { MBoxData mBoxData = null;/* w w w .j ava2s .c o m*/ Message message; try { message = inbox.getMessage(currentMessage); if (logger.isDebugEnabled()) { logger.debug("Processing message " + currentMessage + " of " + messageCount + ""); if (logger.isTraceEnabled()) { logger.trace("------- MESSAGE START -------"); logger.trace(message.getContent().toString()); logger.trace("------- MESSAGE END -------"); } } mBoxData = new MBoxData(message.getContent().toString()); mBoxData.setBody(message.getContent().toString()); StringBuilder stringBuilder = new StringBuilder(); Enumeration<Header> enumeration = message.getAllHeaders(); while (enumeration.hasMoreElements()) { Header header = enumeration.nextElement(); if (header.getName().equalsIgnoreCase("from")) { mBoxData.setOriginator(header.getValue()); } else { stringBuilder.append(header.getValue()); } if (header.getName().equalsIgnoreCase("date")) { String strDate = header.getValue(); Date date = getDate(strDate); mBoxData.setDate(date); } stringBuilder.append('\n'); } mBoxData.setHeader(stringBuilder.toString()); } catch (MessagingException e) { logger.error("Unable to process message " + currentMessage + ": " + e.getMessage(), e); } catch (IOException e) { logger.error("I/O error while processing the message " + currentMessage + ": " + e.getMessage(), e); } currentMessage++; return mBoxData; }
From source file:com.duroty.utils.mail.MessageUtilities.java
public static InternetHeaders getHeadersWithFrom(Message message) throws MessagingException { Header xheader;//from w ww.j a v a2s . com InternetHeaders xheaders = new InternetHeaders(); Enumeration xe = message.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); xheaders.addHeader(xheader.getName(), xheader.getValue()); } return xheaders; }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//from w w w.j a v a 2 s . c o m * * @param message DOCUMENT ME! * * @return DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static InternetHeaders getHeaders(Message message) throws MessagingException { Header xheader; InternetHeaders xheaders = new InternetHeaders(); Enumeration xe = message.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); if (!xheader.getName().startsWith("From ")) { xheaders.addHeader(xheader.getName(), xheader.getValue()); } } return xheaders; }
From source file:be.ibridge.kettle.job.entry.getpop.JobEntryGetPOP.java
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = new Result(nr); result.setResult(false);/*from ww w. j av a 2 s.co m*/ result.setNrErrors(1); FileObject fileObject = null; //Get system properties //Properties prop = System.getProperties(); Properties prop = new Properties(); //Create session object //Session sess = Session.getDefaultInstance(prop,null); Session sess = Session.getInstance(prop, null); sess.setDebug(true); try { int nbrmailtoretrieve = Const.toInt(firstmails, 0); fileObject = KettleVFS.getFileObject(getRealOutputDirectory()); // Check if output folder exists if (!fileObject.exists()) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.FolderNotExists1.Label") + getRealOutputDirectory() + Messages.getString("JobGetMailsFromPOP.FolderNotExists2.Label")); } else { String host = getRealServername(); String user = getRealUsername(); String pwd = getRealPassword(); Store st = null; if (!getUseSSL()) { //Create POP3 object st = sess.getStore("pop3"); // Try to connect to the server st.connect(host, user, pwd); } else { // Ssupports POP3 connection with SSL, the connection is established via SSL. String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //Properties pop3Props = new Properties(); prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); prop.setProperty("mail.pop3.socketFactory.fallback", "false"); prop.setProperty("mail.pop3.port", getRealSSLPort()); prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); st = new POP3SSLStore(sess, url); st.connect(); } log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //Open default folder INBOX Folder f = st.getFolder("INBOX"); f.open(Folder.READ_ONLY); if (f == null) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); } else { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder1.Label") + f.getName() + Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder2.Label") + f.getMessageCount()); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder1.Label") + f.getName() + Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder2.Label") + f.getNewMessageCount()); // Get emails Message msg_list[] = getPOPMessages(f, retrievemails); if (msg_list.length > 0) { List current_file_POP = new ArrayList(); List current_filepath_POP = new ArrayList(); int nb_email_POP = 1; DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy"); String startpattern = "name"; if (!Const.isEmpty(getRealFilenamePattern())) { startpattern = getRealFilenamePattern(); } for (int i = 0; i < msg_list.length; i++) { /*if(msg[i].isMimeType("text/plain")) { log.logDetailed(toString(), "Expediteur: "+msg[i].getFrom()[0]); log.logDetailed(toString(), "Sujet: "+msg[i].getSubject()); log.logDetailed(toString(), "Texte: "+(String)msg[i].getContent()); }*/ if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) { Message msg_POP = msg_list[i]; log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label") + msg_list[i].getFrom()[0]); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailSubject.Label") + msg_list[i].getSubject()); String localfilename_message = startpattern + "_" + dateFormat.format(new Date()) + "_" + (i + 1) + ".mail"; log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LocalFilename1.Label") + localfilename_message + Messages.getString("JobGetMailsFromPOP.LocalFilename2.Label")); File filename_message = new File(getRealOutputDirectory(), localfilename_message); OutputStream os_filename = new FileOutputStream(filename_message); Enumeration enums_POP = msg_POP.getAllHeaders(); while (enums_POP.hasMoreElements()) { Header header_POP = (Header) enums_POP.nextElement(); os_filename.write(new StringBuffer(header_POP.getName()).append(": ") .append(header_POP.getValue()).append("\r\n").toString().getBytes()); } os_filename.write("\r\n".getBytes()); InputStream in_POP = msg_POP.getInputStream(); byte[] buffer_POP = new byte[1024]; int length_POP = 0; while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) { os_filename.write(buffer_POP, 0, length_POP); } os_filename.close(); nb_email_POP++; current_file_POP.add(filename_message); current_filepath_POP.add(filename_message.getPath()); if (delete) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true); } } } } // Close and exit if (f != null) f.close(false); if (st != null) st.close(); f = null; st = null; sess = null; result.setNrErrors(0); result.setResult(true); } } } catch (NoSuchProviderException e) { log.logError(toString(), "provider error: " + e.getMessage()); } catch (MessagingException e) { log.logError(toString(), "Message error: " + e.getMessage()); } catch (Exception e) { log.logError(toString(), "Inexpected error: " + e.getMessage()); } finally { if (fileObject != null) { try { fileObject.close(); } catch (IOException ex) { } ; } sess = null; } return result; }
From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java
@SuppressWarnings({ "unchecked" }) public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = previousResult; result.setResult(false);// www . java 2s. c o m result.setNrErrors(1); //Get system properties Properties prop = new Properties(); prop.setProperty("mail.pop3s.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$ prop.setProperty("mail.pop3.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$ //Create session object Session sess = Session.getDefaultInstance(prop, null); sess.setDebug(true); FileObject fileObject = null; Store st = null; Folder f = null; try { int nbrmailtoretrieve = Const.toInt(firstmails, 0); String realOutputFolder = getRealOutputDirectory(); fileObject = KettleVFS.getFileObject(realOutputFolder); // Check if output folder exists if (!fileObject.exists()) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.FolderNotExists.Label", realOutputFolder)); //$NON-NLS-1$ } else { if (fileObject.getType() == FileType.FOLDER) { String host = getRealServername(); String user = getRealUsername(); String pwd = getRealPassword(); if (!getUseSSL()) { //Create POP3 object st = sess.getStore("pop3"); //$NON-NLS-1$ // Try to connect to the server st.connect(host, user, pwd); } else { // Ssupports POP3 connection with SSL, the connection is established via SSL. String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.fallback", "false"); //$NON-NLS-1$ //$NON-NLS-2$ prop.setProperty("mail.pop3.port", getRealSSLPort()); //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); //$NON-NLS-1$ URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); //$NON-NLS-1$ //$NON-NLS-2$ st = new POP3SSLStore(sess, url); st.connect(); } if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //$NON-NLS-1$ //Open the INBOX FOLDER // For POP3, the only folder available is the INBOX. f = st.getFolder("INBOX"); //$NON-NLS-1$ if (f == null) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); //$NON-NLS-1$ } else { // Open folder if (delete) f.open(Folder.READ_WRITE); else f.open(Folder.READ_ONLY); Message messageList[] = f.getMessages(); if (log.isDetailed()) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder.Label", f.getName(), //$NON-NLS-1$ String.valueOf(messageList.length))); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalUnreadMessagesFolder.Label", //$NON-NLS-1$ f.getName(), String.valueOf(f.getUnreadMessageCount()))); } // Get emails Message msg_list[] = getPOPMessages(f, retrievemails); if (msg_list.length > 0) { List<File> current_file_POP = new ArrayList<File>(); List<String> current_filepath_POP = new ArrayList<String>(); int nb_email_POP = 1; String startpattern = "name"; //$NON-NLS-1$ if (!Const.isEmpty(getRealFilenamePattern())) { startpattern = getRealFilenamePattern(); } for (int i = 0; i < msg_list.length; i++) { if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) { Message msg_POP = msg_list[i]; if (log.isDetailed()) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label", //$NON-NLS-1$ msg_list[i].getFrom()[0].toString())); log.logDetailed(toString(), Messages.getString( "JobGetMailsFromPOP.EmailSubject.Label", msg_list[i].getSubject())); //$NON-NLS-1$ } String localfilename_message = startpattern + "_" //$NON-NLS-1$ + StringUtil.getFormattedDateTimeNow(true) + "_" + (i + 1) + ".mail"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDetailed()) log.logDetailed(toString(), Messages.getString( "JobGetMailsFromPOP.LocalFilename.Label", localfilename_message)); //$NON-NLS-1$ File filename_message = new File(realOutputFolder, localfilename_message); OutputStream os_filename = new FileOutputStream(filename_message); Enumeration<Header> enums_POP = msg_POP.getAllHeaders(); while (enums_POP.hasMoreElements()) { Header header_POP = enums_POP.nextElement(); os_filename.write(new StringBuffer(header_POP.getName()).append(": ") //$NON-NLS-1$ .append(header_POP.getValue()).append("\r\n").toString().getBytes()); //$NON-NLS-1$ } os_filename.write("\r\n".getBytes()); //$NON-NLS-1$ InputStream in_POP = msg_POP.getInputStream(); byte[] buffer_POP = new byte[1024]; int length_POP = 0; while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) { os_filename.write(buffer_POP, 0, length_POP); } os_filename.close(); nb_email_POP++; current_file_POP.add(filename_message); current_filepath_POP.add(filename_message.getPath()); // Check attachments Object content = msg_POP.getContent(); if (content instanceof Multipart) { handleMultipart(realOutputFolder, (Multipart) content); } // Check if mail has to be deleted if (delete) { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); //$NON-NLS-1$ msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true); } } } } result.setNrErrors(0); result.setResult(true); } } else { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.Error.NotAFolder", realOutputFolder)); } } } catch (NoSuchProviderException e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.ProviderException", e.getMessage())); //$NON-NLS-1$ } catch (MessagingException e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.MessagingException", e.getMessage())); //$NON-NLS-1$ } catch (Exception e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.GeneralException", e.getMessage())); //$NON-NLS-1$ } finally { if (fileObject != null) { try { fileObject.close(); } catch (IOException ex) { } ; } //close the folder, passing in a true value to expunge the deleted message try { if (f != null) f.close(true); if (st != null) st.close(); } catch (Exception e) { log.logError(toString(), e.getMessage()); } // free memory f = null; st = null; sess = null; } return result; }
From source file:com.sonicle.webtop.mail.Service.java
public void processGetSource(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { MailAccount account = getAccount(request); String foldername = request.getParameter("folder"); String uid = request.getParameter("id"); String sheaders = request.getParameter("headers"); boolean headers = sheaders.equals("true"); String sout = null;//from w w w.j a va 2 s . c om try { account.checkStoreConnected(); //StringBuffer sb = new StringBuffer("<pre>"); StringBuffer sb = new StringBuffer(); FolderCache mcache = account.getFolderCache(foldername); Message msg = mcache.getMessage(Long.parseLong(uid)); //Folder folder=msg.getFolder(); for (Enumeration e = msg.getAllHeaders(); e.hasMoreElements();) { Header header = (Header) e.nextElement(); //sb.append(MailUtils.htmlescape(header.getName()) + ": " + MailUtils.htmlescape(header.getValue()) + "\n"); sb.append(header.getName() + ": " + header.getValue() + "\n"); } if (!headers) { BufferedReader br = new BufferedReader(new InputStreamReader(msg.getInputStream())); String line = null; while ((line = br.readLine()) != null) { //sb.append(MailUtils.htmlescape(line) + "\n"); sb.append(line + "\n"); } } //sb.append("</pre>"); sout = "{\nresult: true, source: '" + StringEscapeUtils.escapeEcmaScript(sb.toString()) + "'\n}"; } catch (Exception exc) { Service.logger.error("Exception", exc); sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}"; } out.println(sout); }
From source file:org.apache.camel.component.mail.MailBinding.java
protected Map<String, Object> extractHeadersFromMail(Message mailMessage, Exchange exchange) throws MessagingException { Map<String, Object> answer = new HashMap<String, Object>(); Enumeration names = mailMessage.getAllHeaders(); while (names.hasMoreElements()) { Header header = (Header) names.nextElement(); String value = header.getValue(); if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(header.getName(), value, exchange)) { CollectionHelper.appendValue(answer, header.getName(), value); }/* ww w.j av a 2s .c o m*/ } return answer; }
From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java
/** * {@inheritDoc}//from w w w . j ava 2 s .c o m */ @Override public SampleResult sample(Entry e) { SampleResult parent = new SampleResult(); boolean isOK = false; // Did sample succeed? final boolean deleteMessages = getDeleteMessages(); final String serverProtocol = getServerType(); parent.setSampleLabel(getName()); String samplerString = toString(); parent.setSamplerData(samplerString); /* * Perform the sampling */ parent.sampleStart(); // Start timing try { // Create empty properties Properties props = new Properties(); if (isUseStartTLS()) { props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE); // $NON-NLS-1$ if (isEnforceStartTLS()) { // Requires JavaMail 1.4.2+ props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE); // $NON-NLS-1$ } } if (isTrustAllCerts()) { if (isUseSSL()) { props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$ props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } else if (isUseStartTLS()) { props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$ props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } } else if (isUseLocalTrustStore()) { File truststore = new File(getTrustStoreToUse()); log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()); truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse()); log.info("load local truststore -Attempting to read truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution."); throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath()); } } if (isUseSSL()) { // Requires JavaMail 1.4.2+ props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ new LocalTrustStoreSSLSocketFactory(truststore)); props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } else if (isUseStartTLS()) { // Requires JavaMail 1.4.2+ props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ new LocalTrustStoreSSLSocketFactory(truststore)); props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } } // Get session Session session = Session.getInstance(props, null); // Get the store Store store = session.getStore(serverProtocol); store.connect(getServer(), getPortAsInt(), getUserName(), getPassword()); // Get folder Folder folder = store.getFolder(getFolder()); if (deleteMessages) { folder.open(Folder.READ_WRITE); } else { folder.open(Folder.READ_ONLY); } final int messageTotal = folder.getMessageCount(); int n = getNumMessages(); if (n == ALL_MESSAGES || n > messageTotal) { n = messageTotal; } // Get directory Message[] messages = folder.getMessages(1, n); StringBuilder pdata = new StringBuilder(); pdata.append(messages.length); pdata.append(" messages found\n"); parent.setResponseData(pdata.toString(), null); parent.setDataType(SampleResult.TEXT); parent.setContentType("text/plain"); // $NON-NLS-1$ final boolean headerOnly = getHeaderOnly(); busy = true; for (Message message : messages) { StringBuilder cdata = new StringBuilder(); SampleResult child = new SampleResult(); child.sampleStart(); cdata.append("Message "); // $NON-NLS-1$ cdata.append(message.getMessageNumber()); child.setSampleLabel(cdata.toString()); child.setSamplerData(cdata.toString()); cdata.setLength(0); final String contentType = message.getContentType(); child.setContentType(contentType);// Store the content-type child.setDataEncoding(RFC_822_DEFAULT_ENCODING); // RFC 822 uses ascii per default child.setEncodingAndType(contentType);// Parse the content-type if (isStoreMimeMessage()) { // Don't save headers - they are already in the raw message ByteArrayOutputStream bout = new ByteArrayOutputStream(); message.writeTo(bout); child.setResponseData(bout.toByteArray()); // Save raw message child.setDataType(SampleResult.TEXT); } else { @SuppressWarnings("unchecked") // Javadoc for the API says this is OK Enumeration<Header> hdrs = message.getAllHeaders(); while (hdrs.hasMoreElements()) { Header hdr = hdrs.nextElement(); String value = hdr.getValue(); try { value = MimeUtility.decodeText(value); } catch (UnsupportedEncodingException uce) { // ignored } cdata.append(hdr.getName()).append(": ").append(value).append("\n"); } child.setResponseHeaders(cdata.toString()); cdata.setLength(0); if (!headerOnly) { appendMessageData(child, message); } } if (deleteMessages) { message.setFlag(Flags.Flag.DELETED, true); } child.setResponseOK(); if (child.getEndTime() == 0) {// Avoid double-call if addSubResult was called. child.sampleEnd(); } parent.addSubResult(child); } // Close connection folder.close(true); store.close(); parent.setResponseCodeOK(); parent.setResponseMessageOK(); isOK = true; } catch (NoClassDefFoundError | IOException ex) { log.debug("", ex);// No need to log normally, as we set the status parent.setResponseCode("500"); // $NON-NLS-1$ parent.setResponseMessage(ex.toString()); } catch (MessagingException ex) { log.debug("", ex);// No need to log normally, as we set the status parent.setResponseCode("500"); // $NON-NLS-1$ parent.setResponseMessage(ex.toString() + "\n" + samplerString); // $NON-NLS-1$ } finally { busy = false; } if (parent.getEndTime() == 0) {// not been set by any child samples parent.sampleEnd(); } parent.setSuccessful(isOK); return parent; }
From source file:org.apache.jsieve.utils.SieveMailAdapter.java
/** * Parses the value from the given message into addresses. * /*w w w .j a v a 2 s .co m*/ * @param headerName * header name, to be matched case insensitively * @param message * <code>Message</code>, not null * @return <code>Address</code> array, not null possibly empty * @throws SieveMailException */ public Address[] parseAddresses(final String headerName, final Message message) throws SieveMailException { try { final SieveAddressBuilder builder = new SieveAddressBuilder(); for (Enumeration en = message.getAllHeaders(); en.hasMoreElements();) { final Header header = (Header) en.nextElement(); final String name = header.getName(); if (name.trim().equalsIgnoreCase(headerName)) { builder.addAddresses(header.getValue()); } } final Address[] results = builder.getAddresses(); return results; } catch (MessagingException ex) { throw new SieveMailException(ex); } catch (org.apache.jsieve.parser.generated.address.ParseException ex) { throw new SieveMailException(ex); } }
From source file:org.exist.xquery.modules.mail.MessageListFunctions.java
private Sequence getMessageListAsXML(Sequence[] args, Sequence contextSequence) throws XPathException { Message[] msgList;//from w ww. ja v a 2s .co m Sequence ret = Sequence.EMPTY_SEQUENCE; // was a msgList handle specified? if (args[0].isEmpty()) { throw (new XPathException(this, "Message List handle not specified")); } // get the MessageList long msgListHandle = ((IntegerValue) args[0].itemAt(0)).getLong(); msgList = MailModule.retrieveMessageList(context, msgListHandle); if (msgList == null) { throw (new XPathException(this, "Invalid Message List handle specified")); } if (msgList.length > 0) { boolean includeHeaders = args[1].effectiveBooleanValue(); MemTreeBuilder builder = context.getDocumentBuilder(); builder.startDocument(); builder.startElement(new QName("messages", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("count", null, null), String.valueOf(msgList.length)); try { for (int i = 0; i < msgList.length; i++) { Message message = msgList[i]; builder.startElement(new QName("message", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("number", null, null), String.valueOf(message.getMessageNumber())); // Sent Date if (message.getSentDate() != null) { builder.startElement(new QName("sent", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.characters(formatDate(message.getSentDate())); builder.endElement(); } // Received Date if (message.getReceivedDate() != null) { builder.startElement(new QName("received", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.characters(formatDate(message.getReceivedDate())); builder.endElement(); } // From if (message.getFrom() != null) { builder.startElement(new QName("from", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.characters(message.getFrom()[0].toString()); builder.endElement(); } // Recipients builder.startElement(new QName("recipients", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); // To Recipients Address[] toAddresses = message.getRecipients(Message.RecipientType.TO); if (toAddresses != null) { for (Address to : toAddresses) { builder.startElement( new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "to"); builder.characters(to.toString()); builder.endElement(); } } // cc Recipients Address[] ccAddresses = message.getRecipients(Message.RecipientType.CC); if (ccAddresses != null) { for (Address ccAddress : ccAddresses) { builder.startElement( new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "cc"); builder.characters(ccAddress.toString()); builder.endElement(); } } // bcc Recipients Address[] bccAddresses = message.getRecipients(Message.RecipientType.BCC); if (bccAddresses != null) { for (Address bccAddress : bccAddresses) { builder.startElement( new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "bcc"); builder.characters(bccAddress.toString()); builder.endElement(); } } builder.endElement(); // Flags Flags flags = message.getFlags(); Flags.Flag[] systemFlags = flags.getSystemFlags(); String[] userFlags = flags.getUserFlags(); if (systemFlags.length > 0 || userFlags.length > 0) { builder.startElement(new QName("flags", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); for (Flags.Flag systemFlag : systemFlags) { if (systemFlag == Flags.Flag.ANSWERED) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "answered"); builder.endElement(); } else if (systemFlag == Flags.Flag.DELETED) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "deleted"); builder.endElement(); } else if (systemFlag == Flags.Flag.DRAFT) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "draft"); builder.endElement(); } else if (systemFlag == Flags.Flag.FLAGGED) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "flagged"); builder.endElement(); } else if (systemFlag == Flags.Flag.RECENT) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "recent"); builder.endElement(); } else if (systemFlag == Flags.Flag.SEEN) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "seen"); builder.endElement(); } } for (String userFlag : userFlags) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "user"); builder.addAttribute(new QName("value", null, null), userFlag); builder.endElement(); } builder.endElement(); } // Headers if (includeHeaders) { Enumeration headers = message.getAllHeaders(); if (headers.hasMoreElements()) { builder.startElement(new QName("headers", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); while (headers.hasMoreElements()) { Header header = (Header) headers.nextElement(); builder.startElement( new QName("header", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("name", null, null), header.getName()); builder.addAttribute(new QName("value", null, null), header.getValue()); builder.endElement(); } builder.endElement(); } } // Subject builder.startElement(new QName("subject", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.characters(message.getSubject()); builder.endElement(); builder.endElement(); } } catch (MessagingException me) { throw (new XPathException(this, "Failed to retrieve messages from list", me)); } builder.endElement(); ret = (NodeValue) builder.getDocument().getDocumentElement(); } return (ret); }