List of usage examples for javax.mail.internet MimeMessage MimeMessage
protected MimeMessage(Folder folder, int msgnum)
From source file:com.openkm.util.impexp.RepositoryImporter.java
/** * Import mail.// w ww. j a va 2 s . c om */ private static ImpExpStats importMail(String token, String fldPath, String fileName, File fDoc, boolean metadata, Writer out, InfoDecorator deco) throws IOException, PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException { FileInputStream fisContent = new FileInputStream(fDoc); MetadataAdapter ma = MetadataAdapter.getInstance(token); MailModule mm = ModuleManager.getMailModule(); Properties props = System.getProperties(); props.put("mail.host", "smtp.dummydomain.com"); props.put("mail.transport.protocol", "smtp"); ImpExpStats stats = new ImpExpStats(); int size = fisContent.available(); Mail mail = new Mail(); Gson gson = new Gson(); boolean api = false; try { // Metadata if (metadata) { // Read serialized document metadata File jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT); log.info("Document Metadata File: {}", jsFile.getPath()); if (jsFile.exists() && jsFile.canRead()) { FileReader fr = new FileReader(jsFile); MailMetadata mmd = gson.fromJson(fr, MailMetadata.class); mail.setPath(fldPath + "/" + fileName); mmd.setPath(mail.getPath()); IOUtils.closeQuietly(fr); log.info("Mail Metadata: {}", mmd); // Apply metadata ma.importWithMetadata(mmd); // Add attachments if (fileName.endsWith(".eml")) { Session mailSession = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(mailSession, fisContent); mail = MailUtils.messageToMail(msg); mail.setPath(fldPath + "/" + mmd.getName()); MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser()); } else if (fileName.endsWith(".msg")) { Message msg = new MsgParser().parseMsg(fisContent); mail = MailUtils.messageToMail(msg); mail.setPath(fldPath + "/" + mmd.getName()); MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser()); } else { throw new MessagingException("Unknown mail format"); } FileLogger.info(BASE_NAME, "Created document ''{0}''", mail.getPath()); log.info("Created document '{}'", mail.getPath()); } else { log.warn("Unable to read metadata file: {}", jsFile.getPath()); api = true; } } else { api = true; } if (api) { if (fileName.endsWith(".eml")) { Session mailSession = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(mailSession, fisContent); mail = MailUtils.messageToMail(msg); mail.setPath(fldPath + "/" + UUID.randomUUID().toString() + "-" + PathUtils.escape(mail.getSubject())); mm.create(token, mail); MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser()); } else if (fileName.endsWith(".msg")) { Message msg = new MsgParser().parseMsg(fisContent); mail = MailUtils.messageToMail(msg); mail.setPath(fldPath + "/" + UUID.randomUUID().toString() + "-" + PathUtils.escape(mail.getSubject())); mm.create(token, mail); MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser()); } else { throw new MessagingException("Unknown mail format"); } FileLogger.info(BASE_NAME, "Created mail ''{0}''", mail.getPath()); log.info("Created mail ''{}''", mail.getPath()); } if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), null)); out.flush(); } // Stats stats.setSize(stats.getSize() + size); stats.setMails(stats.getMails() + 1); } catch (UnsupportedMimeTypeException e) { log.warn("UnsupportedMimeTypeException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", mail.getPath()); } catch (FileSizeExceededException e) { log.warn("FileSizeExceededException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", mail.getPath()); } catch (UserQuotaExceededException e) { log.warn("UserQuotaExceededException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", mail.getPath()); } catch (VirusDetectedException e) { log.warn("VirusWarningException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", mail.getPath()); } catch (ItemExistsException e) { log.warn("ItemExistsException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", mail.getPath()); } catch (JsonParseException e) { log.warn("JsonParseException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", mail.getPath()); } catch (MessagingException e) { log.warn("MessagingException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "Messaging")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "MessagingException ''{0}''", mail.getPath()); } catch (Exception e) { log.warn("Exception: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "General")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "Exception ''{0}''", mail.getPath()); } finally { IOUtils.closeQuietly(fisContent); } return stats; }
From source file:com.ikon.util.impexp.RepositoryImporter.java
/** * Import mail.//w w w .java 2s. co m */ private static ImpExpStats importMail(String token, File fs, String fldPath, String fileName, File fDoc, String metadata, Writer out, InfoDecorator deco) throws IOException, PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException { FileInputStream fisContent = new FileInputStream(fDoc); MetadataAdapter ma = MetadataAdapter.getInstance(token); MailModule mm = ModuleManager.getMailModule(); Properties props = System.getProperties(); props.put("mail.host", "smtp.dummydomain.com"); props.put("mail.transport.protocol", "smtp"); ImpExpStats stats = new ImpExpStats(); int size = fisContent.available(); Mail mail = new Mail(); Gson gson = new Gson(); boolean api = false; try { // Metadata if (metadata.equals("JSON")) { // Read serialized document metadata File jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT); log.info("Document Metadata File: {}", jsFile.getPath()); if (jsFile.exists() && jsFile.canRead()) { FileReader fr = new FileReader(jsFile); MailMetadata mmd = gson.fromJson(fr, MailMetadata.class); mail.setPath(fldPath + "/" + fileName); mmd.setPath(mail.getPath()); IOUtils.closeQuietly(fr); log.info("Mail Metadata: {}", mmd); // Apply metadata ma.importWithMetadata(mmd); // Add attachments Session mailSession = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(mailSession, fisContent); mail = MailUtils.messageToMail(msg); mail.setPath(fldPath + "/" + mmd.getName()); MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser()); FileLogger.info(BASE_NAME, "Created document ''{0}''", mail.getPath()); log.info("Created document '{}'", mail.getPath()); } else { log.warn("Unable to read metadata file: {}", jsFile.getPath()); api = true; } } else { api = true; } if (api) { Session mailSession = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(mailSession, fisContent); mail = MailUtils.messageToMail(msg); mail.setPath(fldPath + "/" + fileName); mm.create(token, mail); MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser()); FileLogger.info(BASE_NAME, "Created mail ''{0}''", mail.getPath()); log.info("Created mail ''{}''", mail.getPath()); } if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), null)); out.flush(); } // Stats stats.setSize(stats.getSize() + size); stats.setMails(stats.getMails() + 1); } catch (UnsupportedMimeTypeException e) { log.warn("UnsupportedMimeTypeException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", mail.getPath()); } catch (FileSizeExceededException e) { log.warn("FileSizeExceededException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", mail.getPath()); } catch (UserQuotaExceededException e) { log.warn("UserQuotaExceededException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", mail.getPath()); } catch (VirusDetectedException e) { log.warn("VirusWarningException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", mail.getPath()); } catch (ItemExistsException e) { log.warn("ItemExistsException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", mail.getPath()); } catch (JsonParseException e) { log.warn("JsonParseException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", mail.getPath()); } catch (MessagingException e) { log.warn("MessagingException: {}", e.getMessage()); if (out != null) { out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "MessagingException ''{0}''", mail.getPath()); } finally { IOUtils.closeQuietly(fisContent); } return stats; }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Writes a passed payload data to the passed message object. Could be called from either the MDN * processing or the message processing/*from w w w . ja va 2 s. c o m*/ */ public void writePayloadsToMessage(byte[] data, AS2Message message, Properties header) throws Exception { ByteArrayOutputStream payloadOut = new ByteArrayOutputStream(); MimeMessage testMessage = new MimeMessage(Session.getInstance(System.getProperties()), new ByteArrayInputStream(data)); //multiple attachments? if (testMessage.isMimeType("multipart/*")) { this.writePayloadsToMessage(testMessage, message, header); return; } InputStream payloadIn = null; AS2Info info = message.getAS2Info(); if (info instanceof AS2MessageInfo && info.getSignType() == AS2Message.SIGNATURE_NONE && ((AS2MessageInfo) info).getCompressionType() == AS2Message.COMPRESSION_NONE) { payloadIn = new ByteArrayInputStream(data); } else if (testMessage.getSize() > 0) { payloadIn = testMessage.getInputStream(); } else { payloadIn = new ByteArrayInputStream(data); } this.copyStreams(payloadIn, payloadOut); payloadOut.flush(); payloadOut.close(); byte[] payloadData = payloadOut.toByteArray(); AS2Payload as2Payload = new AS2Payload(); as2Payload.setData(payloadData); String contentIdHeader = header.getProperty("content-id"); if (contentIdHeader != null) { as2Payload.setContentId(contentIdHeader); } String contentTypeHeader = header.getProperty("content-type"); if (contentTypeHeader != null) { as2Payload.setContentType(contentTypeHeader); } try { as2Payload.setOriginalFilename(testMessage.getFileName()); } catch (MessagingException e) { if (this.logger != null) { this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error", new Object[] { info.getMessageId(), e.getMessage(), }), info); } } if (as2Payload.getOriginalFilename() == null) { String filenameHeader = header.getProperty("content-disposition"); if (filenameHeader != null) { //test part for convinience: extract file name MimeBodyPart filenamePart = new MimeBodyPart(); filenamePart.setHeader("content-disposition", filenameHeader); try { as2Payload.setOriginalFilename(filenamePart.getFileName()); } catch (MessagingException e) { if (this.logger != null) { this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error", new Object[] { info.getMessageId(), e.getMessage(), }), info); } } } } message.addPayload(as2Payload); }
From source file:fr.gouv.culture.vitam.eml.EmlExtract.java
private static final MimeMessage createOneMessageFromFile(File emlFile) throws FileNotFoundException, MessagingException { Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props); /*props.put("mail.host", "smtp.vitamdomain.com"); props.put("mail.transport.protocol", "smtp"); Session session = Session.getDefaultInstance(props, null);*/ InputStream source = new FileInputStream(emlFile); return new MimeMessage(session, source); }
From source file:davmail.imap.ImapConnection.java
@Override public void run() { final String capabilities; int imapIdleDelay = Settings.getIntProperty("davmail.imapIdleDelay") * 60; if (imapIdleDelay > 0) { capabilities = "CAPABILITY IMAP4REV1 AUTH=LOGIN IDLE MOVE"; } else {//from ww w. j av a 2 s . co m capabilities = "CAPABILITY IMAP4REV1 AUTH=LOGIN MOVE"; } String line; String commandId = null; IMAPTokenizer tokens; try { // ExchangeSessionFactory.checkConfig(); sendClient("* OK [" + capabilities + "] IMAP4rev1 DavMail " + DavGateway.getCurrentVersion() + " server ready"); for (;;) { line = readClient(); // unable to read line, connection closed ? if (line == null) { break; } tokens = new IMAPTokenizer(line); if (tokens.hasMoreTokens()) { commandId = tokens.nextToken(); checkInfiniteLoop(line); if (tokens.hasMoreTokens()) { String command = tokens.nextToken(); if ("LOGOUT".equalsIgnoreCase(command)) { sendClient("* BYE Closing connection"); sendClient(commandId + " OK LOGOUT completed"); break; } if ("capability".equalsIgnoreCase(command)) { sendClient("* " + capabilities); sendClient(commandId + " OK CAPABILITY completed"); } else if ("login".equalsIgnoreCase(command)) { parseCredentials(tokens); // detect shared mailbox access splitUserName(); try { session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else if ("AUTHENTICATE".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String authenticationMethod = tokens.nextToken(); if ("LOGIN".equalsIgnoreCase(authenticationMethod)) { try { sendClient("+ " + base64Encode("Username:")); state = State.LOGIN; userName = base64Decode(readClient()); // detect shared mailbox access splitUserName(); sendClient("+ " + base64Encode("Password:")); state = State.PASSWORD; password = base64Decode(readClient()); session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else { sendClient(commandId + " NO unsupported authentication method"); } } else { sendClient(commandId + " BAD authentication method required"); } } else { if (state != State.AUTHENTICATED) { sendClient(commandId + " BAD command authentication required"); } else { // check for expired session session = ExchangeSessionFactory.getInstance(session, userName, password); if ("lsub".equalsIgnoreCase(command) || "list".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderContext; if (baseMailboxPath == null) { folderContext = BASE64MailboxDecoder.decode(tokens.nextToken()); } else { folderContext = baseMailboxPath + BASE64MailboxDecoder.decode(tokens.nextToken()); } if (tokens.hasMoreTokens()) { String folderQuery = folderContext + BASE64MailboxDecoder.decode(tokens.nextToken()); if (folderQuery.endsWith("%/%") && !"/%/%".equals(folderQuery)) { List<ExchangeSession.Folder> folders = session.getSubFolders( folderQuery.substring(0, folderQuery.length() - 3), false); for (ExchangeSession.Folder folder : folders) { sendClient( "* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendSubFolders(command, folder.folderPath, false); } sendClient(commandId + " OK " + command + " completed"); } else if (folderQuery.endsWith("%") || folderQuery.endsWith("*")) { if ("/*".equals(folderQuery) || "/%".equals(folderQuery) || "/%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(1); if ("%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(0, folderQuery.length() - 2); } sendClient( "* " + command + " (\\HasChildren) \"/\" \"/public\""); } if ("*%".equals(folderQuery)) { folderQuery = "*"; } boolean recursive = folderQuery.endsWith("*") && !folderQuery.startsWith("/public"); sendSubFolders(command, folderQuery.substring(0, folderQuery.length() - 1), recursive); sendClient(commandId + " OK " + command + " completed"); } else { ExchangeSession.Folder folder = null; try { folder = session.getFolder(folderQuery); } catch (HttpForbiddenException e) { // access forbidden, ignore DavGatewayTray.debug(new BundleMessage( "LOG_FOLDER_ACCESS_FORBIDDEN", folderQuery)); } catch (HttpNotFoundException e) { // not found, ignore DavGatewayTray.debug( new BundleMessage("LOG_FOLDER_NOT_FOUND", folderQuery)); } catch (HttpException e) { // other errors, ignore DavGatewayTray .debug(new BundleMessage("LOG_FOLDER_ACCESS_ERROR", folderQuery, e.getMessage())); } if (folder != null) { sendClient( "* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendClient(commandId + " OK " + command + " completed"); } else { sendClient(commandId + " NO Folder not found"); } } } else { sendClient(commandId + " BAD missing folder argument"); } } else { sendClient(commandId + " BAD missing folder argument"); } } else if ("select".equalsIgnoreCase(command) || "examine".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { @SuppressWarnings({ "NonConstantStringShouldBeStringBuffer" }) String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); if (baseMailboxPath != null && !folderName.startsWith("/")) { folderName = baseMailboxPath + folderName; } try { currentFolder = session.getFolder(folderName); currentFolder.loadMessages(); sendClient("* " + currentFolder.count() + " EXISTS"); sendClient("* " + currentFolder.recent + " RECENT"); sendClient("* OK [UIDVALIDITY 1]"); if (currentFolder.count() == 0) { sendClient("* OK [UIDNEXT 1]"); } else { sendClient("* OK [UIDNEXT " + currentFolder.getUidNext() + ']'); } sendClient( "* FLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk)"); sendClient( "* OK [PERMANENTFLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk \\*)]"); if ("select".equalsIgnoreCase(command)) { sendClient( commandId + " OK [READ-WRITE] " + command + " completed"); } else { sendClient(commandId + " OK [READ-ONLY] " + command + " completed"); } } catch (HttpNotFoundException e) { sendClient(commandId + " NO Not found"); } catch (HttpForbiddenException e) { sendClient(commandId + " NO Forbidden"); } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("expunge".equalsIgnoreCase(command)) { if (expunge(false)) { // need to refresh folder to avoid 404 errors session.refreshFolder(currentFolder); } sendClient(commandId + " OK " + command + " completed"); } else if ("close".equalsIgnoreCase(command)) { expunge(true); // deselect folder currentFolder = null; sendClient(commandId + " OK " + command + " completed"); } else if ("create".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); session.createMessageFolder(folderName); sendClient(commandId + " OK folder created"); } else { sendClient(commandId + " BAD missing create argument"); } } else if ("rename".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.moveFolder(folderName, targetName); sendClient(commandId + " OK rename completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("delete".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.deleteFolder(folderName); sendClient(commandId + " OK folder deleted"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("uid".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String subcommand = tokens.nextToken(); if ("fetch".equalsIgnoreCase(subcommand)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { String ranges = tokens.nextToken(); if (ranges == null) { sendClient(commandId + " BAD missing range parameter"); } else { String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } UIDRangeIterator uidRangeIterator = new UIDRangeIterator( currentFolder.messages, ranges); while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); try { handleFetch(message, uidRangeIterator.currentIndex, parameters); } catch (HttpNotFoundException e) { LOGGER.warn("Ignore missing message " + uidRangeIterator.currentIndex); } catch (SocketException e) { // client closed connection throw e; } catch (IOException e) { DavGatewayTray.log(e); sendClient( commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK UID FETCH completed"); } } } else if ("search".equalsIgnoreCase(subcommand)) { List<Long> uidList = handleSearch(tokens); StringBuilder buffer = new StringBuilder("* SEARCH"); for (long uid : uidList) { buffer.append(' '); buffer.append(uid); } sendClient(buffer.toString()); sendClient(commandId + " OK SEARCH completed"); } else if ("store".equalsIgnoreCase(subcommand)) { UIDRangeIterator uidRangeIterator = new UIDRangeIterator( currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, uidRangeIterator, action, flags); } else if ("copy".equalsIgnoreCase(subcommand) || "move".equalsIgnoreCase(subcommand)) { try { UIDRangeIterator uidRangeIterator = new UIDRangeIterator( currentFolder.messages, tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); if (!uidRangeIterator.hasNext()) { sendClient(commandId + " NO " + "No message found"); } else { while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); if ("copy".equalsIgnoreCase(subcommand)) { session.copyMessage(message, targetName); } else { session.moveMessage(message, targetName); } } sendClient(commandId + " OK " + subcommand + " completed"); } } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("search".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { List<Long> uidList = handleSearch(tokens); if (uidList.isEmpty()) { sendClient("* SEARCH"); } else { int currentIndex = 0; for (ExchangeSession.Message message : currentFolder.messages) { currentIndex++; if (uidList.contains(message.getImapUid())) { sendClient("* SEARCH " + currentIndex); } } } sendClient(commandId + " OK SEARCH completed"); } } else if ("fetch".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } while (rangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = rangeIterator.next(); try { handleFetch(message, rangeIterator.currentIndex, parameters); } catch (HttpNotFoundException e) { LOGGER.warn("Ignore missing message " + rangeIterator.currentIndex); } catch (SocketException e) { // client closed connection, rethrow exception throw e; } catch (IOException e) { DavGatewayTray.log(e); sendClient(commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK FETCH completed"); } } else if ("store".equalsIgnoreCase(command)) { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, rangeIterator, action, flags); } else if ("copy".equalsIgnoreCase(command) || "move".equalsIgnoreCase(command)) { try { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); if (!rangeIterator.hasNext()) { sendClient(commandId + " NO " + "No message found"); } else { while (rangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = rangeIterator.next(); if ("copy".equalsIgnoreCase(command)) { session.copyMessage(message, targetName); } else { session.moveMessage(message, targetName); } } sendClient(commandId + " OK " + command + " completed"); } } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("append".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); HashMap<String, String> properties = new HashMap<String, String>(); String flags = null; String date = null; // handle optional flags String nextToken = tokens.nextQuotedToken(); if (nextToken.startsWith("(")) { flags = StringUtil.removeQuotes(nextToken); if (tokens.hasMoreTokens()) { nextToken = tokens.nextToken(); if (tokens.hasMoreTokens()) { date = nextToken; nextToken = tokens.nextToken(); } } } else if (tokens.hasMoreTokens()) { date = StringUtil.removeQuotes(nextToken); nextToken = tokens.nextToken(); } if (flags != null) { // parse flags, on create read and draft flags are on the // same messageFlags property, 8 means draft and 1 means read StringTokenizer flagtokenizer = new StringTokenizer(flags); while (flagtokenizer.hasMoreTokens()) { String flag = flagtokenizer.nextToken(); if ("\\Seen".equals(flag)) { if (properties.containsKey("draft")) { // draft message, add read flag properties.put("draft", "9"); } else { // not (yet) draft, set read flag properties.put("draft", "1"); } } else if ("\\Flagged".equals(flag)) { properties.put("flagged", "2"); } else if ("\\Answered".equals(flag)) { properties.put("answered", "102"); } else if ("$Forwarded".equals(flag)) { properties.put("forwarded", "104"); } else if ("\\Draft".equals(flag)) { if (properties.containsKey("draft")) { // read message, add draft flag properties.put("draft", "9"); } else { // not (yet) read, set draft flag properties.put("draft", "8"); } } else if ("Junk".equals(flag)) { properties.put("junk", "1"); } } } else { // no flags, force not draft and unread properties.put("draft", "0"); } // handle optional date if (date != null) { SimpleDateFormat dateParser = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z", Locale.ENGLISH); Date dateReceived = dateParser.parse(date); SimpleDateFormat dateFormatter = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE); properties.put("datereceived", dateFormatter.format(dateReceived)); } int size = Integer.parseInt(StringUtil.removeQuotes(nextToken)); sendClient("+ send literal data"); byte[] buffer = in.readContent(size); // empty line readClient(); MimeMessage mimeMessage = new MimeMessage(null, new SharedByteArrayInputStream(buffer)); String messageName = UUID.randomUUID().toString() + ".EML"; try { session.createMessage(folderName, messageName, properties, mimeMessage); sendClient(commandId + " OK APPEND completed"); } catch (InsufficientStorageException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("idle".equalsIgnoreCase(command) && imapIdleDelay > 0) { if (currentFolder != null) { sendClient("+ idling "); // clear cache before going to idle mode currentFolder.clearCache(); DavGatewayTray.resetIcon(); try { int count = 0; while (in.available() == 0) { if (++count >= imapIdleDelay) { count = 0; TreeMap<Long, String> previousImapFlagMap = currentFolder .getImapFlagMap(); if (session.refreshFolder(currentFolder)) { handleRefresh(previousImapFlagMap, currentFolder.getImapFlagMap()); } } // sleep 1 second Thread.sleep(1000); } // read DONE line line = readClient(); if ("DONE".equals(line)) { sendClient(commandId + " OK " + command + " terminated"); } else { sendClient(commandId + " BAD command unrecognized"); } } catch (IOException e) { // client connection closed throw new SocketException(e.getMessage()); } } else { sendClient(commandId + " NO no folder selected"); } } else if ("noop".equalsIgnoreCase(command) || "check".equalsIgnoreCase(command)) { if (currentFolder != null) { DavGatewayTray.debug(new BundleMessage("LOG_IMAP_COMMAND", command, currentFolder.folderPath)); TreeMap<Long, String> previousImapFlagMap = currentFolder.getImapFlagMap(); if (session.refreshFolder(currentFolder)) { handleRefresh(previousImapFlagMap, currentFolder.getImapFlagMap()); } } sendClient(commandId + " OK " + command + " completed"); } else if ("subscribe".equalsIgnoreCase(command) || "unsubscribe".equalsIgnoreCase(command)) { sendClient(commandId + " OK " + command + " completed"); } else if ("status".equalsIgnoreCase(command)) { try { String encodedFolderName = tokens.nextToken(); String folderName = BASE64MailboxDecoder.decode(encodedFolderName); ExchangeSession.Folder folder = session.getFolder(folderName); // must retrieve messages folder.loadMessages(); String parameters = tokens.nextToken(); StringBuilder answer = new StringBuilder(); StringTokenizer parametersTokens = new StringTokenizer(parameters); while (parametersTokens.hasMoreTokens()) { String token = parametersTokens.nextToken(); if ("MESSAGES".equalsIgnoreCase(token)) { answer.append("MESSAGES ").append(folder.count()).append(' '); } if ("RECENT".equalsIgnoreCase(token)) { answer.append("RECENT ").append(folder.recent).append(' '); } if ("UIDNEXT".equalsIgnoreCase(token)) { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { answer.append("UIDNEXT ").append(folder.getUidNext()) .append(' '); } } } if ("UIDVALIDITY".equalsIgnoreCase(token)) { answer.append("UIDVALIDITY 1 "); } if ("UNSEEN".equalsIgnoreCase(token)) { answer.append("UNSEEN ").append(folder.unreadCount).append(' '); } } sendClient("* STATUS \"" + encodedFolderName + "\" (" + answer.toString().trim() + ')'); sendClient(commandId + " OK " + command + " completed"); } catch (HttpException e) { sendClient(commandId + " NO folder not found"); } } else { sendClient(commandId + " BAD command unrecognized"); } } } } else { sendClient(commandId + " BAD missing command"); } } else { sendClient("BAD Null command"); } DavGatewayTray.resetIcon(); } os.flush(); } catch (SocketTimeoutException e) { DavGatewayTray.debug(new BundleMessage("LOG_CLOSE_CONNECTION_ON_TIMEOUT")); try { sendClient("* BYE Closing connection"); } catch (IOException e1) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_CLOSING_CONNECTION_ON_TIMEOUT")); } } catch (SocketException e) { LOGGER.warn(BundleMessage.formatLog("LOG_CLIENT_CLOSED_CONNECTION")); } catch (Exception e) { DavGatewayTray.log(e); try { String message = ((e.getMessage() == null) ? e.toString() : e.getMessage()).replaceAll("\\n", " "); if (commandId != null) { sendClient(commandId + " BAD unable to handle request: " + message); } else { sendClient("* BAD unable to handle request: " + message); } } catch (IOException e2) { DavGatewayTray.warn(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { close(); } DavGatewayTray.resetIcon(); }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * Given a message that we are replying to, or forwarding, * * @param part The part to decode./*from ww w . j a v a2 s . c o m*/ * @param buffer The new message body text buffer. * @param dmailParts Vector for new message's attachments. * * @return The buffer being filled in with the body. * * @throws MessagingException DOCUMENT ME! * @throws IOException */ protected static StringBuffer subDecodeContent(Part part, StringBuffer buffer, Vector dmailParts, boolean chooseHtml, String breakLine) throws MessagingException, IOException { boolean attachIt = true; // decode based on content type and disposition ContentType xctype = MessageUtilities.getContentType(part); ContentDisposition xcdisposition = MessageUtilities.getContentDisposition(part); if (xctype.match("multipart/*")) { attachIt = false; Multipart xmulti = (Multipart) MessageUtilities.getPartContent(part); int xparts = 0; try { xparts = xmulti.getCount(); } catch (MessagingException e) { attachIt = true; xparts = 0; } for (int xindex = 0; xindex < xparts; xindex++) { MessageUtilities.subDecodeContent(xmulti.getBodyPart(xindex), buffer, dmailParts, chooseHtml, breakLine); } } else if (xctype.match("message/rfc822")) { MimeMessage newMessage = new MimeMessage((Session) null, part.getInputStream()); decodeContent(newMessage, buffer, dmailParts, chooseHtml, breakLine); } else if (xctype.match("text/plain") && !chooseHtml) { if (xcdisposition.match("inline")) { attachIt = false; String xjcharset = xctype.getParameter("charset"); if (xjcharset == null) { // not present, assume ASCII character encoding try { Header xheader; Enumeration xe = part.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); String aux = xheader.getName().toLowerCase().trim(); if (aux.indexOf("subject") > -1) { int pos1 = aux.indexOf("=?"); int pos2 = aux.indexOf("?q?"); if ((pos1 > -1) && (pos2 > -1)) { xjcharset = aux.substring(pos1, pos2); } break; } } } catch (Exception ex) { System.out.print(ex.getMessage()); } if (xjcharset == null) { xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms } } MessageUtilities.decodeTextPlain(buffer, part, breakLine, xjcharset); } } else if (xctype.match("text/html") && chooseHtml) { if (xcdisposition.match("inline")) { attachIt = false; String xjcharset = xctype.getParameter("charset"); if (xjcharset == null) { // not present, assume ASCII character encoding try { Header xheader; Enumeration xe = part.getAllHeaders(); for (; xe.hasMoreElements();) { xheader = (Header) xe.nextElement(); String aux = xheader.getName().toLowerCase().trim(); if (aux.indexOf("subject") > -1) { int pos1 = aux.indexOf("=?"); int pos2 = aux.indexOf("?q?"); if ((pos1 > -1) && (pos2 > -1)) { xjcharset = aux.substring(pos1, pos2); } break; } } } catch (Exception ex) { } if (xjcharset == null) { xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms } } MessageUtilities.decodeTextHtml(buffer, part, xjcharset); } } if (attachIt) { // UNDONE should simple single line entries be // created for other types and attachments? // // UNDONE should attachements only be created for "attachments" or all // unknown content types? if (dmailParts != null) { MailPart aux = new MailPart(); aux.setPart(part); aux.setId(dmailParts.size()); aux.setName(MessageUtilities.encodeStringToXml(MessageUtilities.getPartName(part))); aux.setContentType(xctype.getBaseType()); aux.setSize(part.getSize()); dmailParts.addElement(aux); } } return buffer; }
From source file:davmail.exchange.dav.DavExchangeSession.java
/** * Send message.//from w w w. j a v a 2 s . com * * @param messageBody MIME message body * @throws IOException on error */ public void sendMessage(byte[] messageBody) throws IOException { try { sendMessage(new MimeMessage(null, new SharedByteArrayInputStream(messageBody))); } catch (MessagingException e) { throw new IOException(e.getMessage()); } }
From source file:com.flexoodb.common.FlexUtils.java
/** * method to obtain a FileContainer containing the file wrapped in a mimemessage. * * @param data the mimemessage in a byte array. * @return a FileContainer containing the file. *///from w w w. j av a 2 s .co m static public FileContainer extractFileFromMimeMessage(byte[] data) throws Exception { FileContainer fc = null; MimeMessage message = new MimeMessage(null, new ByteArrayInputStream(data)); Object content = message.getContent(); if (content instanceof Multipart) { Multipart multipart = (Multipart) content; for (int i = 0, n = multipart.getCount(); i < n; i++) { Part part = multipart.getBodyPart(i); String disposition = part.getDisposition(); if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE)))) { if (part.getFileName() != null) { fc = new FileContainer(part.getFileName(), part.getFileName(), getBytesFromInputStream(part.getInputStream())); break; } } } } return fc; }
From source file:com.sonicle.webtop.mail.Service.java
public void processUploadToFolder(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { try {/*from www .j av a2 s.c o m*/ MailAccount account = getAccount(request); String currentFolder = request.getParameter("folder"); String uploadId = request.getParameter("uploadId"); UploadedFile upfile = getUploadedFile(uploadId); InputStream in = new FileInputStream(upfile.getFile()); MimeMessage msgContent = new MimeMessage(account.getMailSession(), in); FolderCache tomcache = account.getFolderCache(currentFolder); msgContent.setFlag(Flags.Flag.SEEN, true); tomcache.appendMessage(msgContent); new JsonResult().printTo(out); } catch (Exception exc) { logger.debug("Cannot upload to folder", exc); new JsonResult("Cannot upload to folder", exc).printTo(out); } }