List of usage examples for javax.mail Folder READ_WRITE
int READ_WRITE
To view the source code for javax.mail Folder READ_WRITE.
Click Source Link
From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
@Override public boolean deleteMessages(MailStoreConfiguration config, String[] uuids) { Authenticator auth = credentialsProvider.getAuthenticator(); Folder inbox = null;// ww w . ja v a 2s . c o m try { // Retrieve user's inbox Session session = openMailSession(config, auth); inbox = getUserInbox(session, config.getInboxFolderName()); // Verify that we can even perform this operation if (!(inbox instanceof UIDFolder)) { String msg = "Delete feature is supported only for UIDFolder instances"; throw new UnsupportedOperationException(msg); } inbox.open(Folder.READ_WRITE); Message[] msgs = ((UIDFolder) inbox).getMessagesByUID(getMessageUidsAsLong(uuids)); inbox.setFlags(msgs, new Flags(Flag.DELETED), true); return true; // Indicate success } catch (MessagingException e) { log.error("Messaging exception while deleting messages", e); } finally { if (inbox != null) { try { inbox.close(false); } catch (Exception e) { log.warn("Can't close correctly javamail inbox connection"); } try { inbox.getStore().close(); } catch (Exception e) { log.warn("Can't close correctly javamail store connection"); } } } return false; // We failed if we reached this point }
From source file:com.ikon.util.MailUtils.java
/** * Import messages/*from w w w . jav a 2 s .com*/ * http://www.jguru.com/faq/view.jsp?EID=26898 * * == Using Unique Identifier (UIDL) == * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email, * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't * receive it; otherwise receive it. * * == Different property of UIDL in POP3 and IMAP4 == * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is * no longer exist on the POP3 server. * * == Remarks == * You should create different local uidl list for different email account, because the uidl is only * unique for the same account. */ public static String importMessages(String token, MailAccount ma) throws PathNotFoundException, ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException, DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException { log.debug("importMessages({}, {})", new Object[] { token, ma }); Session session = Session.getDefaultInstance(getProperties()); String exceptionMessage = null; try { // Open connection Store store = session.getStore(ma.getMailProtocol()); store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword()); Folder folder = store.getFolder(ma.getMailFolder()); folder.open(Folder.READ_WRITE); Message messages[] = null; if (folder instanceof IMAPFolder) { // IMAP folder UIDs begins at 1 and are supposed to be sequential. // Each folder has its own UIDs sequence, not is a global one. messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID); } else { messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; log.info(i + ": " + msg.getFrom()[0] + " " + msg.getSubject() + " " + msg.getContentType()); log.info("Received: " + msg.getReceivedDate()); log.info("Sent: " + msg.getSentDate()); log.debug("{} -> {} - {}", new Object[] { i, msg.getSubject(), msg.getReceivedDate() }); com.ikon.bean.Mail mail = messageToMail(msg); if (ma.getMailFilters().isEmpty()) { log.debug("Import in compatibility mode"); String mailPath = getUserMailPath(ma.getUser()); importMail(token, mailPath, true, folder, msg, ma, mail); } else { for (MailFilter mf : ma.getMailFilters()) { log.debug("MailFilter: {}", mf); if (checkRules(mail, mf.getFilterRules())) { String mailPath = mf.getPath(); importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail); } } } // Set message as seen if (ma.isMailMarkSeen()) { msg.setFlag(Flags.Flag.SEEN, true); } else { msg.setFlag(Flags.Flag.SEEN, false); } // Delete read mail if requested if (ma.isMailMarkDeleted()) { msg.setFlag(Flags.Flag.DELETED, true); } // Set lastUid if (folder instanceof IMAPFolder) { long msgUid = ((IMAPFolder) folder).getUID(msg); log.info("Message UID: {}", msgUid); ma.setMailLastUid(msgUid); MailAccountDAO.update(ma); } } // Close connection log.debug("Expunge: {}", ma.isMailMarkDeleted()); folder.close(ma.isMailMarkDeleted()); store.close(); } catch (NoSuchProviderException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (MessagingException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (IOException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } log.debug("importMessages: {}", exceptionMessage); return exceptionMessage; }
From source file:com.openkm.util.MailUtils.java
/** * Import messages// www . j av a2s . c om * http://www.jguru.com/faq/view.jsp?EID=26898 * * == Using Unique Identifier (UIDL) == * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email, * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't * receive it; otherwise receive it. * * == Different property of UIDL in POP3 and IMAP4 == * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is * no longer exist on the POP3 server. * * == Remarks == * You should create different local uidl list for different email account, because the uidl is only * unique for the same account. */ public static String importMessages(String token, MailAccount ma) throws PathNotFoundException, ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException, DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException { log.debug("importMessages({}, {})", new Object[] { token, ma }); Session session = Session.getDefaultInstance(getProperties()); String exceptionMessage = null; try { // Open connection Store store = session.getStore(ma.getMailProtocol()); store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword()); Folder folder = store.getFolder(ma.getMailFolder()); folder.open(Folder.READ_WRITE); Message messages[] = null; if (folder instanceof IMAPFolder) { // IMAP folder UIDs begins at 1 and are supposed to be sequential. // Each folder has its own UIDs sequence, not is a global one. messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID); } else { messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; log.info("======= ======= {} ======= =======", i); log.info("Subject: {}", msg.getSubject()); log.info("From: {}", msg.getFrom()); log.info("Received: {}", msg.getReceivedDate()); log.info("Sent: {}", msg.getSentDate()); com.openkm.bean.Mail mail = messageToMail(msg); if (ma.getMailFilters().isEmpty()) { log.debug("Import in compatibility mode"); String mailPath = getUserMailPath(ma.getUser()); importMail(token, mailPath, true, folder, msg, ma, mail); } else { for (MailFilter mf : ma.getMailFilters()) { log.debug("MailFilter: {}", mf); if (checkRules(mail, mf.getFilterRules())) { String mailPath = mf.getPath(); importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail); } } } // Set message as seen if (ma.isMailMarkSeen()) { msg.setFlag(Flags.Flag.SEEN, true); } else { msg.setFlag(Flags.Flag.SEEN, false); } // Delete read mail if requested if (ma.isMailMarkDeleted()) { msg.setFlag(Flags.Flag.DELETED, true); } // Set lastUid if (folder instanceof IMAPFolder) { long msgUid = ((IMAPFolder) folder).getUID(msg); log.info("Message UID: {}", msgUid); ma.setMailLastUid(msgUid); MailAccountDAO.update(ma); } } // Close connection log.debug("Expunge: {}", ma.isMailMarkDeleted()); folder.close(ma.isMailMarkDeleted()); store.close(); } catch (NoSuchProviderException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (MessagingException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (IOException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } log.debug("importMessages: {}", exceptionMessage); return exceptionMessage; }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Fetch a message from a folder.//from w w w . jav a2s . co m * Will put the messages parameters in the sessions environment * * @param foldername Name of the folder were the message should be fetched from * @param msgnum Number of the message to fetch * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message * into the current work element of the user and set some additional flags on the message if the user * has enabled this option. * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD */ public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException { // security reasons: // attachments=null; try { TimeZone tz = TimeZone.getDefault(); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, user.getPreferredLocale()); df.setTimeZone(tz); Folder folder = getFolder(folderhash); Element xml_folder = model.getFolder(folderhash); if (folder == null) { throw new NoSuchFolderException("No such folder: " + folderhash); } if (folder.isOpen() && folder.getMode() == Folder.READ_WRITE) { folder.close(false); folder.open(Folder.READ_ONLY); } else if (!folder.isOpen()) { folder.open(Folder.READ_ONLY); } MimeMessage m = (MimeMessage) folder.getMessage(msgnum); String messageid; try { StringTokenizer tok = new StringTokenizer(m.getMessageID(), "<>"); messageid = tok.nextToken(); } catch (NullPointerException ex) { // For mail servers that don't generate a Message-ID (Outlook et al) messageid = user.getLogin() + "." + msgnum + ".jwebmail@" + user.getDomain(); } Element xml_current = model.setCurrentMessage(messageid); XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid); /* Check whether we already cached this message (not only headers but complete)*/ boolean cached = xml_message.messageCompletelyCached(); /* If we cached the message, we don't need to fetch it again */ if (!cached) { //Element xml_header=model.getHeader(xml_message); try { String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom())); String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo())); String to = MimeUtility .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO))); String cc = MimeUtility .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC))); String bcc = MimeUtility .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC))); Date date_orig = m.getSentDate(); String date = getStringResource("no date"); if (date_orig != null) { date = df.format(date_orig); } String subject = ""; if (m.getSubject() != null) { subject = MimeUtility.decodeText(m.getSubject()); } if (subject == null || subject.equals("")) { subject = getStringResource("no subject"); } try { Flags.Flag[] sf = m.getFlags().getSystemFlags(); for (int j = 0; j < sf.length; j++) { if (sf[j] == Flags.Flag.RECENT) xml_message.setAttribute("recent", "true"); if (sf[j] == Flags.Flag.SEEN) xml_message.setAttribute("seen", "true"); if (sf[j] == Flags.Flag.DELETED) xml_message.setAttribute("deleted", "true"); if (sf[j] == Flags.Flag.ANSWERED) xml_message.setAttribute("answered", "true"); if (sf[j] == Flags.Flag.DRAFT) xml_message.setAttribute("draft", "true"); if (sf[j] == Flags.Flag.FLAGGED) xml_message.setAttribute("flagged", "true"); if (sf[j] == Flags.Flag.USER) xml_message.setAttribute("user", "true"); } } catch (NullPointerException ex) { } if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) { xml_message.setAttribute("attachment", "true"); } int size = m.getSize(); size /= 1024; xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB"); /* Set all of what we found into the DOM */ xml_message.setHeader("FROM", from); xml_message.setHeader("SUBJECT", Fancyfier.apply(subject)); xml_message.setHeader("TO", to); xml_message.setHeader("CC", cc); xml_message.setHeader("BCC", bcc); xml_message.setHeader("REPLY-TO", replyto); xml_message.setHeader("DATE", date); /* Decode MIME contents recursively */ xml_message.removeAllParts(); parseMIMEContent(m, xml_message, messageid); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage()); } } /* Set seen flag (Maybe make that threaded to improve performance) */ if (user.wantsSetFlags()) { if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) { folder.close(false); folder.open(Folder.READ_WRITE); } else if (!folder.isOpen()) { folder.open(Folder.READ_WRITE); } folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true); folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false); if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) { folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true); } } folder.close(false); /* In this part we determine whether the message was requested so that it may be used for further editing (replying or forwarding). In this case we set the current "work" message to the message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */ XMLMessage work = null; if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) { log.debug("Setting work message!"); work = model.setWorkMessage(xml_message); String newmsgid = WebMailServer.generateMessageID(user.getUserName()); if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) { String from = work.getHeader("FROM"); work.setHeader("FROM", user.getDefaultEmail()); work.setHeader("TO", from); work.prepareReply(getStringResource("reply subject prefix"), getStringResource("reply subject postfix"), getStringResource("reply message prefix"), getStringResource("reply message postfix")); } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) { String from = work.getHeader("FROM"); work.setHeader("FROM", user.getDefaultEmail()); work.setHeader("TO", ""); work.setHeader("CC", ""); work.prepareForward(getStringResource("forward subject prefix"), getStringResource("forward subject postfix"), getStringResource("forward message prefix"), getStringResource("forward message postfix")); /* Copy all references to MIME parts to the new message id */ for (String key : getMimeParts(work.getAttribute("msgid"))) { StringTokenizer tok2 = new StringTokenizer(key, "/"); tok2.nextToken(); String newkey = tok2.nextToken(); mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key)); } } /* Clear the msgnr and msgid fields at last */ work.setAttribute("msgnr", "0"); work.setAttribute("msgid", newmsgid); prepareCompose(); } } catch (MessagingException ex) { log.error("Failed to get message. Doing nothing instead.", ex); } }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
public SetMessageResponseType archiveMessage(SetMessageRequestType request) { SetMessageResponseType response = new SetMessageResponseType(); IMAPSSLStore sslStore = null;/*www. j a v a2 s . c om*/ Folder folder = null; Folder destinationFolder = null; Properties prop = initializeMailProperties(); Session session = Session.getDefaultInstance(prop); // INPUT: request.getUserId() //Get email address and password from LDAP String userId = request.getUserId(); ContactDAO contactDAO = LdapService.getContactDAO(); ContactDTO foundContact = new ContactDTO(); List<ContactDTO> contacts = contactDAO.findAllContacts(); for (ContactDTO contact : contacts) { if (contact.getUid() != null && contact.getUid().equals(request.getUserId())) { foundContact = contact; break; } } String userType = ""; String[] access = new String[2]; String userCName = foundContact.getCommonName(); if (contacts.isEmpty()) { log.error("Contact record not found for user: " + userCName); response.setMessage("Contact record not found for user: " + userCName); response.setSuccessStatus(false); return response; } access = retrieveMailAccess(userCName, foundContact.getUid()); //TMN if ((access[0] == null) || access[0].isEmpty()) { log.error("Contact record not found for user: " + userId); response.setMessage("Contact record not found for user: " + userId); response.setSuccessStatus(false); return response; } //PROCESSING the action. // folder --> the current folder the msg being processed is in. // destinationFolder --> the destination folder where the msg will be moved. try { //---------------------------------- // Determine/Set destination folder //---------------------------------- if (request.getAction().equals("Archive")) { destinationFolder = getImapFolder(session, sslStore, access, "Archives"); } else if (request.getAction().equals("Unarchive")) { destinationFolder = getImapFolder(session, sslStore, access, "INBOX"); } destinationFolder.open(Folder.READ_WRITE); //---------------------------------- // Set originating folder //---------------------------------- folder = getImapFolder(session, sslStore, access, this.mapKmrLocationToImapFolder(request.getLocation(), this.host)); folder.open(Folder.READ_WRITE); System.out.println( "===> DMD.archiveMessage: " + request.getAction() + "-ing for msgId=" + request.getMessageId() + "\n===> from " + folder.getName() + " to folder=" + destinationFolder.getName()); //-------------------------------------------- // Find the message by the given Message-ID //-------------------------------------------- IMAPMessage imapMessage = (IMAPMessage) findMsgByMessageId(folder, request.getMessageId()); //-------------------------------------------- // Process the message //-------------------------------------------- if (imapMessage != null) { Message[] messages = new Message[] { imapMessage }; folder.copyMessages(messages, destinationFolder); imapMessage.setFlag(Flags.Flag.DELETED, true); folder.expunge(); System.out.println("===> DMD.archiveMessage: Done " + request.getAction() + " for msgId=" + request.getMessageId()); response.setSuccessStatus(true); } else { String statMsg = "Msg NOT found for Message-ID=" + request.getMessageId(); System.out.println("===> " + statMsg); response.setSuccessStatus(false); response.setMessage(statMsg); } } catch (Exception e) { log.error(e.getMessage()); response.setMessage( "Error " + request.getAction() + " mail with Zimbra mail server: " + e.getMessage()); response.setSuccessStatus(false); e.printStackTrace(); return response; } finally { try { if ((folder != null) && folder.isOpen()) folder.close(false); if ((destinationFolder != null) && destinationFolder.isOpen()) destinationFolder.close(false); } catch (MessagingException me) { me.printStackTrace(); } } return response; }
From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
@Override public boolean setMessageReadStatus(MailStoreConfiguration config, String[] uuids, boolean read) { Authenticator auth = credentialsProvider.getAuthenticator(); Folder inbox = null;/* w w w. j a va 2s. com*/ try { // Retrieve user's inbox Session session = openMailSession(config, auth); inbox = getUserInbox(session, config.getInboxFolderName()); // Verify that we can even perform this operation log info if it isn't capable of operation if (!(inbox instanceof UIDFolder)) { String msg = "Toggle unread feature is supported only for UIDFolder instances"; log.info(msg); return false; } inbox.open(Folder.READ_WRITE); Message[] msgs = ((UIDFolder) inbox).getMessagesByUID(getMessageUidsAsLong(uuids)); inbox.setFlags(msgs, new Flags(Flag.SEEN), read); return true; // Indicate success } catch (MessagingException e) { log.error("Messaging exception while deleting messages", e); } finally { if (inbox != null) { try { inbox.close(false); } catch (Exception e) { log.warn("Can't close correctly javamail inbox connection"); } try { inbox.getStore().close(); } catch (Exception e) { log.warn("Can't close correctly javamail store connection"); } } } return false; // We failed if we reached this point }
From source file:com.funambol.email.items.manager.ImapEntityManager.java
/** * clean all folder and email except the 5 main folders * * @param allMailboxActivation boolean/*from w ww.ja v a 2 s.c o m*/ * @param source_uri String * @param principalId long * @throws EntityException */ public void clearAllItems(boolean allMailboxActivation, String source_uri, long principalId, String username) throws EntityException { IMAPFolder f = null; EntityException finalExc = null; String[] folders = { this.imsw.getDefaultFolder().getInboxName(), this.imsw.getDefaultFolder().getOutboxName(), this.imsw.getDefaultFolder().getSentName(), this.imsw.getDefaultFolder().getDraftsName(), this.imsw.getDefaultFolder().getTrashName() }; String folderName; // clean all emails in the main folders for (int y = 0; y < folders.length; y++) { folderName = folders[y]; try { f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(folderName); if (log.isTraceEnabled()) { log.trace("ImapEmail Delete all emails in " + folderName); } if (f.exists()) { timeStart = System.currentTimeMillis(); f.open(Folder.READ_WRITE); this.ied.removeAllEmail(f); } } catch (MessagingException me) { throw new EntityException(me); } finally { if (f != null) { try { if (f.isOpen()) { f.close(true); timeStop = System.currentTimeMillis(); if (log.isTraceEnabled()) { log.trace("insertItem Execution Time: " + (timeStop - timeStart) + " ms"); } } } catch (MessagingException me) { finalExc = new EntityException(me); } } } if (finalExc != null) { throw finalExc; } } // clean all folders in the main folders // only if allMalboxActivation is on if (allMailboxActivation) { ArrayList fs; String tmpname; String GUID; IMAPFolder tmpfolder; for (int y = 0; y < folders.length; y++) { folderName = folders[y]; try { f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(folderName); if (log.isTraceEnabled()) { log.trace("ImapEmail Delete all folders in " + folderName); } if (f.exists()) { timeStart = System.currentTimeMillis(); f.open(Folder.READ_WRITE); fs = new ArrayList(); this.ied.searchSubFolderFullNames(f, fs); for (int i = 0; i < fs.size(); i++) { tmpname = (String) fs.get(i); if (log.isTraceEnabled()) { log.trace("remove folder " + tmpname); } // remove folder from Mail Server tmpfolder = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(tmpname); if (tmpfolder.exists()) { // the folder must be closed this.ied.removeFolderInServer(tmpfolder); } // remove folder from Local DB GUID = this.ied.getGUIDFromFullPath(Def.SEPARATOR_FIRST + tmpname, source_uri, principalId, username); this.ied.removeFolderInDB(GUID, source_uri, principalId, username); } } } catch (MessagingException me) { throw new EntityException(me); } finally { if (f != null) { try { if (f.isOpen()) { f.close(true); timeStop = System.currentTimeMillis(); if (log.isTraceEnabled()) { log.trace("insertItem Execution Time: " + (timeStop - timeStart) + " ms"); } } } catch (MessagingException me) { finalExc = new EntityException(me); } } } if (finalExc != null) { throw finalExc; } } } }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
/** * * @param request//w w w . ja v a2 s . c o m * where request.action = [ "Send" , "Update" ,"Read" , "Save" ] * @return */ private SetMessageResponseType sendImapSSLMail(SetMessageRequestType request) { //System.out.println("===> sendImapSSLMail: Action= " + request.getAction()); SetMessageResponseType response = new SetMessageResponseType(); IMAPSSLStore sslStore = null; Folder folder = null; //the email server folder the msg is CURRENTLY in. String userType = ""; String[] access = new String[2]; Properties prop = initializeMailProperties(); Session session = Session.getDefaultInstance(prop); //Get email address and password from LDAP String userId = request.getUserId(); ContactDTO foundContact = null; try { foundContact = findContactByUserId(userId); } catch (Exception e) { log.error("Contact record not found for userid: " + request.getUserId()); response.setMessage("Contact record not found for userid: " + request.getUserId()); response.setSuccessStatus(false); return response; } access = retrieveMailAccess(foundContact.getCommonName(), foundContact.getUid()); if ((access[0] == null) || access[0].isEmpty()) { log.error("Contact record not found for user: " + userId); response.setMessage("Contact record not found for user: " + userId); response.setSuccessStatus(false); return response; } // Use the sslStore to send/change the message try { //action = Save if (request.getAction().equalsIgnoreCase("Save")) { response = saveDraft(request, access, sslStore, this.mapKmrLocationToImapFolder("Drafts", this.host), session); response.setSuccessStatus(true); //return response; } //action = Send else if (request.getAction().equalsIgnoreCase("Send")) { // create and send msg to recipient(s). Message[] msgArr = createMessage(session, access[0], request); sendMessagesTOCCBCC(msgArr, request, session); // Store a copy to sender's Sent folder folder = getImapFolder(session, sslStore, access, this.mapKmrLocationToImapFolder("Sent", this.host)); folder.appendMessages(msgArr); response.setSuccessStatus(true); } //action = ..any other.. else { folder = getImapFolder(session, sslStore, access, this.mapKmrLocationToImapFolder(request.getLocation(), this.host)); folder.open(Folder.READ_WRITE); //-------------------------------------------- // Find the message by the given Message-ID //-------------------------------------------- IMAPMessage imapMessage = (IMAPMessage) findMsgByMessageId(folder, request.getMessageId()); //-------------------------------------------- // Process the message //-------------------------------------------- if (imapMessage != null) { System.out.println("===> sendImapSSLMail:Updating: action=" + request.getAction()); System.out.println("===> sendImapSSLMail:Updating: folder=" + folder.getName()); System.out.println("===> sendImapSSLMail:Updating:ImapMsgID=" + imapMessage.getMessageID()); updateImapSSLMail(request, folder, imapMessage); System.out.println("===> sendImapSSLMail: Done Setting " + request.getAction() + " for msgId=" + request.getMessageId()); response.setSuccessStatus(true); } else { String statMsg = "Msg NOT found for Message-ID=" + request.getMessageId(); System.out.println("===> sendImapSSLMail: " + statMsg); response.setSuccessStatus(false); response.setMessage(statMsg); } } } catch (Exception e) { log.error(e.getMessage()); response.setMessage("Error sending mail with Zimbra mail server: " + e.getMessage()); response.setSuccessStatus(false); return response; } finally { if (folder != null && folder.isOpen()) { try { folder.close(false); } catch (MessagingException me) { log.error("Error closing folder"); } } if (sslStore != null) { try { sslStore.close(); } catch (MessagingException me) { log.error("Error closing SSLStore"); } } } return response; }
From source file:com.funambol.email.items.manager.ImapEntityManager.java
/** * * * @param FID folder id String// ww w. ja v a2 s . c o m * @param LUID String * @param emailToAdd Email * @param filter EmailFilter * @param funSignature String * @param from String * @param firstname String * @param lastname String * @param username String * @param source_uri String * @param principalId long * @return Email * @throws EntityException */ public Email addEmail(String FID, String LUID, Email emailToAdd, Map serverItems, EmailFilter filter, String funSignature, String from, String firstname, String lastname, String username, String source_uri, long principalId) throws EntityException, SendingException, RefusedItemException { IMAPFolder f = null; String fullpath = null; // the emailItem could be null // i.e. the client send only the read property FlagProperties fp = Utility.getFlags(emailToAdd); if (emailToAdd != null && emailToAdd.getEmailItem() != null && Def.ENCODE_QUOTED_PRINTABLE.equals(emailToAdd.getEmailItem().getEncoding())) { try { emailToAdd.getEmailItem().setPropertyValue( Utility.decode(emailToAdd.getEmailItem().getStringRFC2822(), Def.ENCODE_QUOTED_PRINTABLE)); emailToAdd.getEmailItem().setEncoding(null); } catch (MessagingException e) { throw new EntityException(e); } } try { if (FID.equalsIgnoreCase(Def.FOLDER_OUTBOX_ID)) { // OUTBOX - sending procedure (email with id starts with "O") FID = Def.FOLDER_SENT_ID; // convert Email into Message (javaMail) Message msg = createMessage(this.imsw.getSession(), emailToAdd, FID, false, fp); // save message-ID String messageID = Utility.getHeaderMessageID(msg); // send message Message newMsg = null; try { newMsg = sendEmail(msg, this.imsw.getSession(), funSignature, from, firstname, lastname); } catch (SendingException se) { throw new SendingException(se); } if (newMsg != null) { if (messageID != null) { newMsg.setHeader(Def.HEADER_MESSAGE_ID, messageID); } newMsg.setFlag(Flags.Flag.SEEN, true); } else { if (messageID != null) { msg.setHeader(Def.HEADER_MESSAGE_ID, messageID); } } if (Def.SERVER_TYPE_AOL.equals(this.serverType) || Def.SERVER_TYPE_GMAIL.equals(this.serverType)) { // // The email is stored in the SENT folder by the AOL server // and Gmail imap. // // don't save the email in the sent folder emailToAdd.setParentId(new Property(Def.FOLDER_OUTBOX_ID)); String GUID = Utility.createIMAPGUID(Def.FOLDER_OUTBOX_ID, String.valueOf(LUID), String.valueOf(0)); emailToAdd.setUID(new Property(GUID)); // if the item is not saved in the sent folder the system // doesn't add it into the servetItems list return emailToAdd; } else { // the SENT folder could be disable // if it's enabled the system adds the item in the sent // folder of the Mail Server // get Sent folder name fullpath = this.ied.getFullPathFromFID(FID, source_uri, principalId, username); if (fullpath == null) { emailToAdd.setParentId(new Property(Def.FOLDER_OUTBOX_ID)); String GUID = Utility.createIMAPGUID(Def.FOLDER_OUTBOX_ID, String.valueOf(LUID), String.valueOf(0)); emailToAdd.setUID(new Property(GUID)); return emailToAdd; } // open Sent Folder on mail server f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(fullpath); if (!f.exists()) { emailToAdd.setParentId(new Property(Def.FOLDER_OUTBOX_ID)); String GUID = Utility.createIMAPGUID(Def.FOLDER_OUTBOX_ID, String.valueOf(LUID), String.valueOf(0)); emailToAdd.setUID(new Property(GUID)); return emailToAdd; } timeStart = System.currentTimeMillis(); f.open(Folder.READ_WRITE); long uid = -1; if (this.serverType.equals(Def.SERVER_TYPE_COURIER)) { if (newMsg != null) { uid = this.ied.addEmailByNextUID(f, newMsg); } else { uid = this.ied.addEmailByNextUID(f, msg); } } else { if (newMsg != null) { uid = this.ied.addEmailByListener(f, newMsg); } else { uid = this.ied.addEmailByListener(f, msg); } } emailToAdd.setParentId(new Property(Def.FOLDER_OUTBOX_ID)); long uidv = f.getUIDValidity(); String GUID = Utility.createIMAPGUID(Def.FOLDER_OUTBOX_ID, String.valueOf(uid), String.valueOf(uidv)); emailToAdd.setUID(new Property(GUID)); // create the object to add in db and in serverItems SyncItemInfo sii = createInfo(GUID, msg, null, Def.PROTOCOL_IMAP); // add email to the servetItems list this.ied.addItemInServerItems(sii, serverItems); return emailToAdd; } } else { /** * this procedure should be tested with client that syncs * items into the the folders: INBOX - SENT - DRAFT - TRASH * At the moment the Funambol client doesn't sync the * previous folders. */ // INBOX - SENT - DRAFT - TRASH if (this.isFolderActive(FID, filter)) { fullpath = this.ied.getFullPathFromFID(FID, source_uri, principalId, username); if (fullpath == null) { return emailToAdd; } f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(fullpath); if (!f.exists()) { //emailToAdd.setUID(new Property(LUID)); return emailToAdd; } // convert Email into Message (javaMail) Message msg = createMessage(this.imsw.getSession(), emailToAdd, FID, false, fp); checkIfItHasToBeRefused(msg); // add in the folder of the Mail Server timeStart = System.currentTimeMillis(); f.open(Folder.READ_WRITE); long uid = -1; if (this.serverType.equals(Def.SERVER_TYPE_COURIER)) { uid = this.ied.addEmailByNextUID(f, msg); } else { uid = this.ied.addEmailByListener(f, msg); } long uidv = f.getUIDValidity(); String GUID = Utility.createIMAPGUID(FID, String.valueOf(uid), String.valueOf(uidv)); emailToAdd.setUID(new Property(GUID)); // create the object to add in db and in serverItems SyncItemInfo sii = createInfo(GUID, msg, null, Def.PROTOCOL_IMAP); if (FID.equalsIgnoreCase(Def.FOLDER_INBOX_ID)) { // add email into the inbox table this.ied.addEmailInDB(sii, username, Def.PROTOCOL_IMAP); } // add email to the servetItems list this.ied.addItemInServerItems(sii, serverItems); return emailToAdd; } else { return emailToAdd; } } } catch (MessagingException me) { throw new EntityException(me); } catch (SendingException e) { throw new SendingException(e); } finally { if (f != null) { try { if (f.isOpen()) { f.close(true); timeStop = System.currentTimeMillis(); if (log.isTraceEnabled()) { log.trace("insertItem Execution Time: " + (timeStop - timeStart) + " ms"); } } } catch (MessagingException me) { throw new EntityException(me); } } } }
From source file:com.funambol.email.items.manager.ImapEntityManager.java
/** * todo understand the type of a folder (holds folders and mails) * * @param name String/*from w w w.j a va 2 s. c o m*/ * @param parentId String * @param df DefaultFolder * @param idFolderSpace IdSpaceGenerator * @param source_uri String * @param principalId long * @return Folder * @throws EntityException */ public com.funambol.email.pdi.folder.Folder addFolder(String name, String parentId, DefaultFolder df, DBIDGenerator idFolderSpace, Map serverItems, String source_uri, long principalId, String username) throws EntityException { com.funambol.email.pdi.folder.Folder folderOut; ItemFolder itemFolder = null; String GUID = null; IMAPFolder f = null; // parent folder String parentFullpath; String fullpath; String role; String creationDate; EntityException finalExc = null; try { parentFullpath = this.ied.getFullPathFromGUID(parentId, source_uri, principalId, username); if (parentFullpath != null) { fullpath = parentFullpath + Def.SEPARATOR_FIRST + name; } else { fullpath = Def.SEPARATOR_FIRST + name; } if (log.isTraceEnabled()) { log.trace("addFolder FID:" + parentFullpath + " FMID:" + fullpath); } boolean isDefFolder = Utility.defaultFolderChecker(df, fullpath); if (isDefFolder) { GUID = Utility.getDefaultFolderId(df, fullpath); } else { f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(parentFullpath); timeStart = System.currentTimeMillis(); f.open(Folder.READ_WRITE); Folder folderToInsert = f.getFolder(name); int type = 0; // set the right folder type if (!folderToInsert.exists()) { GUID = this.ied.addFolder(fullpath, parentId, folderToInsert, type, idFolderSpace, source_uri, principalId, username); } // set the values for the post update operation SyncItemInfo sii = createInfo(GUID); // update email to the servetItems list this.ied.addItemInServerItems(sii, serverItems); } role = Utility.getFolderRole(name, this.imsw.getDefaultFolder()); creationDate = Utility.getFolderCreationDate(); itemFolder = setItemFolder(GUID, name, parentId, role, creationDate); } catch (MessagingException me) { throw new EntityException("Error searching folder", me); } catch (EntityException ee) { throw new EntityException("Error creating folder", ee); } finally { if (f != null) { try { if (f.isOpen()) { f.close(true); timeStop = System.currentTimeMillis(); if (log.isTraceEnabled()) { log.trace("insertFolder Execution Time: " + (timeStop - timeStart) + " ms"); } } } catch (MessagingException me) { finalExc = new EntityException(me); } } } if (finalExc != null) { throw finalExc; } try { folderOut = createFoundationFolder(itemFolder); } catch (Exception e) { throw new EntityException(e); } return folderOut; }