List of usage examples for javax.mail Message getInputStream
public InputStream getInputStream() throws IOException, MessagingException;
From source file:de.mmichaelis.maven.mojo.MailDevelopersMojoTest.java
private void doTestMailToDevelopers(final int numDevelopers) throws Exception { final MavenProject project = mock(MavenProject.class); when(project.getDevelopers()).thenReturn(Arrays.asList(Arrays.copyOf(developers, numDevelopers))); mojoWrapper.setProject(project);/*ww w . j a v a 2 s.com*/ mojoWrapper.execute(); for (int i = 0; i < numDevelopers; i++) { final Developer developer = developers[i]; final Mailbox inbox = Mailbox.get(developer.getEmail()); assertEquals("Should have received one email.", 1, inbox.size()); final Message message = inbox.get(0); final InputStream stream = message.getInputStream(); final int messageSize = message.getSize(); final StringWriter writer; try { writer = new StringWriter(messageSize < 0 ? 512 : messageSize); IOUtils.copy(stream, writer); } finally { stream.close(); } LOG.debug("Mail for one developer:\n" + writer.toString()); } }
From source file:com.canoo.webtest.plugins.emailtest.EmailMessageContentFilter.java
protected void filterContent(final Message message) throws MessagingException { if (StringUtils.isEmpty(getPartIndex())) { try {// ww w .jav a2s . c o m defineAsCurrentResponse(IOUtils.toString(message.getInputStream()), message.getContentType()); return; } catch (IOException e) { throw new MessagingException("Error extracting message: " + e.getMessage()); } } final int partIndex = ConversionUtil.convertToInt(getPartIndex(), 0); try { final Object content = message.getContent(); if (content instanceof Multipart) { extractMultiPartMessage((Multipart) content, partIndex); return; } extractSimpleMessage((String) content, partIndex); } catch (IOException e) { LOG.error("Error processing email message: ", e); throw new MessagingException("Error processing email message: " + e.getMessage()); } }
From source file:com.jlgranda.fede.ejb.mail.reader.EmailHelper.java
/** * get the full Mail from a message//from w ww .ja v a 2 s . c o m * * @param message * @return * @throws MessagingException * @throws IOException */ public String fullMail(javax.mail.Message message) throws MessagingException, IOException { StringBuffer sBuf = new StringBuffer(); @SuppressWarnings("unchecked") Enumeration<javax.mail.Header> headers = message.getAllHeaders(); while (headers.hasMoreElements()) { javax.mail.Header header = headers.nextElement(); sBuf.append(header.getName()).append(": ").append(header.getValue()).append("\n"); } sBuf.append(fromInputStream(message.getInputStream())); return sBuf.toString(); }
From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java
private ResultClass<Boolean> parseSubjectAndCreate(MessageBox messageBox, Message msg) throws MessagingException, IOException { ResultClass<Boolean> result = new ResultClass<>(); Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(messageBox.getSubject()); if (m.matches()) { String mimeType = msg.getAllHeaders() + msg.getContentType(); String key = getStorageKey(Long.parseLong(m.group(3))); storageManager.putObject(bucket, key, mimeType, msg.getInputStream()); String aaa = storageManager.getUrl(bucket, key).toExternalForm(); messageBox.setFile(aaa);/*from w w w . j a va2 s .co m*/ if (("group").equalsIgnoreCase(m.group(2))) { Group group = serviceGroup.getGroupFormatter(Long.parseLong(m.group(3))); if (group != null) { group.getMessages().add(messageBox); result = serviceGroup.updateGroup(group); } } else if (("course").equalsIgnoreCase(m.group(2))) { Course course = serviceCourse.getCourseFormatter(Long.parseLong(m.group(3))); if (course != null) { course.getMessages().add(messageBox); result = serviceCourse.updateCourse(course); } } } return result; }
From source file:fr.gouv.culture.vitam.eml.EmlExtract.java
private static final String handleMessage(Message message, Element metadata, Element prop, String id, VitamArgument argument, ConfigLoader config) throws IOException, MessagingException { Object content = message.getContent(); String[] cte = message.getHeader("Content-Transfer-Encoding"); String[] aresult = null;/* w w w . ja v a2 s .c om*/ if (cte != null && cte.length > 0) { aresult = extractContentType(message.getContentType(), cte[0]); } else { aresult = extractContentType(message.getContentType(), null); } String result = ""; if (content instanceof String) { Element body = XmlDom.factory.createElement("body"); body.addAttribute("mime", aresult[0]); if (aresult[1] != null) { body.addAttribute("charset", aresult[1]); } metadata.add(body); //result = saveBody((String) content.toString(), aresult, id, argument, config); result = saveBody(message.getInputStream(), aresult, id, argument, config); } else if (content instanceof Multipart) { // handle multi part prop.addAttribute(EMAIL_FIELDS.hasAttachment.name, "true"); Multipart mp = (Multipart) content; Element identification = XmlDom.factory.createElement(EMAIL_FIELDS.attachments.name); String value = handleMultipart(mp, identification, id, argument, config); if (identification.hasContent()) { metadata.add(identification); } if (argument.extractKeyword) { result = value; } } return result; }
From source file:com.cubusmail.gwtui.server.services.ShowMessageSourceServlet.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//from ww w. ja v a2 s . c o m String messageId = request.getParameter("messageId"); if (messageId != null) { IMailbox mailbox = SessionManager.get().getMailbox(); Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId)); ContentType contentType = new ContentType("text/plain"); response.setContentType(contentType.getBaseType()); response.setHeader("expires", "0"); String charset = null; if (msg.getContentType() != null) { try { charset = new ContentType(msg.getContentType()).getParameter("charset"); } catch (Throwable e) { // should never happen } } if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) { charset = CubusConstants.DEFAULT_CHARSET; } OutputStream outputStream = response.getOutputStream(); // writing the header String header = generateHeader(msg); outputStream.write(header.getBytes(), 0, header.length()); BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream()); InputStreamReader reader = null; try { reader = new InputStreamReader(bufInputStream, charset); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); reader = new InputStreamReader(bufInputStream); } OutputStreamWriter writer = new OutputStreamWriter(outputStream); char[] inBuf = new char[1024]; int len = 0; try { while ((len = reader.read(inBuf)) > 0) { writer.write(inBuf, 0, len); } } catch (Throwable e) { logger.warn("Download canceled!"); } writer.flush(); writer.close(); outputStream.flush(); outputStream.close(); } } catch (Exception e) { logger.error(e.getMessage(), e); } }
From source file:com.cubusmail.server.services.ShowMessageSourceServlet.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/* w w w . ja va 2 s . c om*/ String messageId = request.getParameter("messageId"); if (messageId != null) { IMailbox mailbox = SessionManager.get().getMailbox(); Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId)); ContentType contentType = new ContentType("text/plain"); response.setContentType(contentType.getBaseType()); response.setHeader("expires", "0"); String charset = null; if (msg.getContentType() != null) { try { charset = new ContentType(msg.getContentType()).getParameter("charset"); } catch (Throwable e) { // should never happen } } if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) { charset = CubusConstants.DEFAULT_CHARSET; } OutputStream outputStream = response.getOutputStream(); // writing the header String header = generateHeader(msg); outputStream.write(header.getBytes(), 0, header.length()); BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream()); InputStreamReader reader = null; try { reader = new InputStreamReader(bufInputStream, charset); } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); reader = new InputStreamReader(bufInputStream); } OutputStreamWriter writer = new OutputStreamWriter(outputStream); char[] inBuf = new char[1024]; int len = 0; try { while ((len = reader.read(inBuf)) > 0) { writer.write(inBuf, 0, len); } } catch (Throwable e) { log.warn("Download canceled!"); } writer.flush(); writer.close(); outputStream.flush(); outputStream.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } }
From source file:fr.gouv.culture.vitam.eml.EmlExtract.java
private static final String handleMessageRecur(Message message, Element identification, String id, VitamArgument argument, ConfigLoader config) throws IOException, MessagingException { Object content = message.getContent(); String result = ""; if (content instanceof String) { String[] cte = message.getHeader("Content-Transfer-Encoding"); String[] aresult = null;//from www .j a v a 2 s .c o m if (cte != null && cte.length > 0) { aresult = extractContentType(message.getContentType(), cte[0]); } else { aresult = extractContentType(message.getContentType(), null); } Element emlroot = XmlDom.factory.createElement("body"); // <identity format="Internet Message Format" mime="message/rfc822" puid="fmt/278" extensions="eml"/> Element subidenti = XmlDom.factory.createElement("identification"); Element identity = XmlDom.factory.createElement("identity"); identity.addAttribute("format", "Internet Message Body Format"); identity.addAttribute("mime", aresult[0] != null ? aresult[0] : "unknown"); identity.addAttribute("extensions", aresult[3] != null ? aresult[3].substring(1) : "unknown"); if (aresult[1] != null) { identity.addAttribute("charset", aresult[1]); } identification.add(identity); emlroot.add(subidenti); identification.add(emlroot); //result += " " + saveBody((String) content.toString(), aresult, id, argument, config); result += " " + saveBody(message.getInputStream(), aresult, id, argument, config); // ignore string } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; if (argument.extractKeyword) { result = handleMultipartRecur(mp, identification, id, argument, config); } else { handleMultipartRecur(mp, identification, id, argument, config); } // handle multi part } return result; }
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 a v a 2s . c o 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);//from w w w.jav a 2 s . co 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; }