List of usage examples for javax.mail URLName URLName
public URLName(String url)
From source file:org.masukomi.aspirin.core.RemoteDelivery.java
public Collection getMXRecordsForHost(String hostName) { Vector recordsColl = null;//w w w . j a va 2 s . c o m try { Record[] records = new Lookup(hostName, Type.MX).run(); // Sort in MX priority (high number is lower priority) if (records != null) Arrays.sort(records, new Comparator() { @Override public int compare(Object arg0, Object arg1) { return ((MXRecord) arg0).getPriority() - ((MXRecord) arg1).getPriority(); } }); // Note: alteration here since above may be null recordsColl = records != null ? new Vector(records.length) : new Vector(); for (int i = 0; i < records.length; i++) { // if records was null .size() will be zero causing this to just skip MXRecord mx = (MXRecord) records[i]; String targetString = mx.getTarget().toString(); URLName uName = new URLName( RemoteDelivery.SMTPScheme + targetString.substring(0, targetString.length() - 1)); recordsColl.add(uName); // System.out.println("Host " + uName.getHost() + " has // preference " + mx.getPriority()); } // No existing MX records can either mean: // 1. the server doesn't do mail because it doesn't exist. // 2. the server doesn't need another host to do its mail. // If the server resolves, assume it does its own mail. if (recordsColl.size() <= 0) { Record[] recordsTypeA = new Lookup(hostName, Type.A).run(); if (recordsTypeA != null && recordsTypeA.length > 0) { recordsColl.addElement(new URLName(RemoteDelivery.SMTPScheme + hostName)); } } } catch (TextParseException e) { log.warn(e); } return recordsColl; }
From source file:edu.ku.brc.helpers.EMailHelper.java
/** * Retrieves a list of all the available messages. For POP3 it checks the local mailbox and downloads any on the server. * For IMAP it returns any in the INBOX. * @param msgList the list to be filled//from w w w . j a va 2 s .c o m * @return true if not erros, false if an error occurred. */ public static boolean getAvailableMsgs(java.util.List<javax.mail.Message> msgList) { boolean status = false; // assume it will fail msgList.clear(); try { String usernameStr = AppPreferences.getRemote().get("settings.email.username", null); //$NON-NLS-1$ String passwordStr = Encryption .decrypt(AppPreferences.getRemote().get("settings.email.password", null)); //$NON-NLS-1$ String emailStr = AppPreferences.getRemote().get("settings.email.email", null); //$NON-NLS-1$ String smtpStr = AppPreferences.getRemote().get("settings.email.smtp", null); //$NON-NLS-1$ String serverNameStr = AppPreferences.getRemote().get("settings.email.servername", null); //$NON-NLS-1$ String acctTypeStr = AppPreferences.getRemote().get("settings.email.accounttype", null); //$NON-NLS-1$ String localMailBoxStr = AppPreferences.getRemote().get("settings.email.localmailbox", null); //$NON-NLS-1$ EMailHelper.AccountType acctType = EMailHelper.getAccountType(acctTypeStr); if (!hasEMailSettings(usernameStr, passwordStr, emailStr, smtpStr, serverNameStr, acctTypeStr, localMailBoxStr)) { JOptionPane.showMessageDialog(UIRegistry.getMostRecentWindow(), getResourceString("EMailHelper.EMAIL_SET_NOT_VALID")); //$NON-NLS-1$ } // Open Local Box if POP if (acctTypeStr.equals(getResourceString("EMailHelper.POP3"))) //$NON-NLS-1$ { try { Properties props = new Properties(); Session session = Session.getDefaultInstance(props); Store store = session.getStore(new URLName("mstor:" + localMailBoxStr)); //$NON-NLS-1$ store.connect(); status = getMessagesFromInbox(store, msgList); // closes everything } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex); instance.lastErrorMsg = ex.toString(); ex.printStackTrace(); status = false; } } else { throw new RuntimeException("Unknown Account Type [" + acctTypeStr + "] must be POP3 or IMAP"); // XXX FIXME //$NON-NLS-1$ //$NON-NLS-2$ } // Try to download message from pop account try { Properties props = System.getProperties(); Session session = Session.getInstance(props, null); if (acctType == AccountType.POP3) { Store store = session.getStore("pop3"); //$NON-NLS-1$ store.connect(serverNameStr, usernameStr, passwordStr); status = getMessagesFromInbox(store, msgList); // closes everything } else if (acctType == AccountType.IMAP) { Store store = session.getStore("imap"); //$NON-NLS-1$ store.connect(serverNameStr, usernameStr, passwordStr); status = getMessagesFromInbox(store, msgList); // closes everything } else { String msgStr = getResourceString("EMailHelper.UNKNOWN_ACCT_TYPE")// //$NON-NLS-1$ + acctTypeStr + getResourceString("EMailHelper.ACCT_TYPE_MUST_BE"); // XXX// //$NON-NLS-2$ instance.lastErrorMsg = msgStr; throw new RuntimeException(msgStr); // XXX FIXME } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex); instance.lastErrorMsg = ex.toString(); status = false; } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex); instance.lastErrorMsg = ex.toString(); status = false; } return status; }
From source file:com.adaptris.mail.MailReceiverCase.java
protected static final URLName createURLName(String urlString, String uname, String pw) throws PasswordException { URLName url = new URLName(urlString); String password = url.getPassword(); String username = url.getUsername(); if (username == null && !isEmpty(uname)) { username = uname;/*from w w w . j av a2 s .c om*/ } if (url.getPassword() == null && pw != null) { password = Password.decode(pw); } return new URLName(url.getProtocol(), url.getHost(), url.getPort(), url.getFile(), username, password); }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
/** * Retrieve mail for user./*ww w . j a va 2s. com*/ * * @param userType = "P" if logged in user is a provider * "T" if logged in user is a patient * @param userId = unique id of logged in user. * @param login = email server user name of logged in user. * @param pswd = password of logged in user. * @param folderName = * @param displayName = full name * @param onlyNew = * * @return * @throws java.lang.Exception */ //private //DBG ONLY - REMOVE COMMENT MARKS public List<SummaryData> retrieveMail(String userType, String userId, String patientId, String login, String pswd, String folderName, String patientName, boolean onlyNew, String mailHost, String mailUrl) throws Exception, DatatypeConfigurationException { List<SummaryData> dataList = new LinkedList<SummaryData>(); IMAPSSLStore sslStore = null; IMAPFolder currentFolder = null; String folderToOpen = folderName; System.out.println("===> retrieveMail Incoming params:"); System.out.println("===> mailHost=" + mailHost); System.out.println("===> mailUrl=" + mailUrl); System.out.println("===> maillogin=" + login); System.out.println("===> folderName=" + folderName); try { //Get session Session session = Session.getInstance(new Properties()); URLName urlName = new URLName(mailUrl); //Get the sslStore sslStore = new IMAPSSLStore(session, urlName); sslStore.connect(mailHost, login, pswd); folderToOpen = this.mapKmrLocationToImapFolder(folderName, this.host); currentFolder = (IMAPFolder) sslStore.getFolder(folderToOpen); currentFolder.open(Folder.READ_ONLY); Message[] allMessages = currentFolder.getMessages(); GregorianCalendar cal = new GregorianCalendar(); System.out.println("====> FILTER PARAMS for Emails:"); System.out.println("====> folder = " + folderToOpen); System.out.println("====> User = " + login); // System.out.println("====> from = "+ patientName +"/"+ patientEmail); // System.out.println("====> ptid = "+ patientId); System.out.println("====> Total Emails found = " + allMessages.length); System.out.println(); // TMN - CHECK SLOW PERFORMANCE ISSUE HERE: //Loop through each email and find ONLY the ones required for return. for (Message msg : allMessages) { if (msg == null) { continue; } // Keep this in case we want to search entire message // // OutputStream os = new ByteArrayOutputStream(); // msg.writeTo(os); // String msgContent = os.toString(); SummaryData summaryData = new SummaryData(); summaryData.setDataSource(DATA_SOURCE); String from = ""; Address[] fromAddr = msg.getFrom(); if (fromAddr != null && fromAddr.length > 0) { String fromFull = fromAddr[0].toString(); from = getContactIdFromEmail(extractEmailAddressFromSender(fromFull)); //System.out.println("retrieveMail: FROM=" + fromFull + " ldap.cn=" + from); } //------------------------------------------------------ //FILTERING: Check to exclude email if // 0) patientId is passed in as a param // AND 1) email does NOT contain PATIENTID=<patientId> // AND 2) email FROM field <> patientName // AND 3) email FROM field <> patientEmail. // // because must becoming from EMR inbox and looking for emails // addressed to userId BUT only ABOUT or FROM patientId. //------------------------------------------------------ summaryData.setFrom(from); summaryData.setAuthor(summaryData.getFrom()); cal.setTime(msg.getReceivedDate()); summaryData.setDateCreated(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal)); summaryData.setDescription(msg.getSubject()); summaryData.setItemId(userType + userId + ITEM_ID_SEPARATER + msg.getFolder().getName() + ITEM_ID_SEPARATER + msg.getHeader("Message-ID")[0]); //this.printMsgIdSubject(msg); //DBG printout boolean msgRead = msg.isSet(Flags.Flag.SEEN); addNameValue(summaryData.getItemValues(), ITEM_READ, String.valueOf(msgRead)); boolean msgStar = msg.isSet(Flags.Flag.FLAGGED); if (msgStar) { addNameValue(summaryData.getItemValues(), ITEM_STARRED, "Starred"); } addNameValue(summaryData.getItemValues(), ITEM_REPLIED, String.valueOf(msg.isSet(Flags.Flag.ANSWERED))); addNameValue(summaryData.getItemValues(), "MESSAGE_TYPE", msg.getFolder().getName()); if (onlyNew) { if (!msg.isSet(Flags.Flag.SEEN)) { dataList.add(summaryData); } } else { dataList.add(summaryData); } } } catch (MessagingException me) { log.error("Error in processing email"); me.printStackTrace(); } finally { // Close connections if (currentFolder != null) { try { currentFolder.close(false); } catch (Exception e) { } } if (sslStore != null) { try { sslStore.close(); } catch (Exception e) { } } } return dataList; }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
/** * IN USE/*w w w . ja va 2s .c o m*/ * * @param request * @return * @throws Exception */ public GetMessageDetailResponseType getMessageDetail(GetMessageDetailRequestType request) throws Exception { System.out.println("===> DMD.getMessageDetail: Looking for msgId=" + request.getMessageId()); System.out.println("===> DMD.getMessageDetail: request patientId=" + request.getPatientId()); System.out.println("===> DMD.getMessageDetail: request userId=" + request.getUserId()); GetMessageDetailResponseType response = new GetMessageDetailResponseType(); IMAPFolder msgFolder = null; IMAPSSLStore sslStore = null; Properties prop = initializeMailProperties(); Session session = Session.getDefaultInstance(prop); //------------------------------------------------------------------ // When patientId is given, access must be from EMR Inbox. // Get email msgs from Patient's email account. // Else // Get email msgs from logged in user's email account. //------------------------------------------------------------------ ContactDTO contact = null; String userType = ""; String[] access = new String[2]; if (!CommonUtil.strNullorEmpty(request.getPatientId())) { contact = contactDAO.findContact("uid=" + request.getPatientId()).get(0); userType = ITEM_ID_PATIENT; } else { contact = contactDAO.findContact("uid=" + request.getUserId()).get(0); userType = ITEM_ID_PROVIDER; } access = retrieveMailAccess(contact.getCommonName(), contact.getUid()); try { session = Session.getInstance(new Properties()); URLName urlName = new URLName(mailUrl); //-------------------------------------------- //Get the sslStore and connect //-------------------------------------------- sslStore = new IMAPSSLStore(session, urlName); sslStore.connect(host, access[0], access[1]); //-------------------------------------------- // Set the originating folder. // Default to INBOX if not given. // Get and open the IMAP folder //-------------------------------------------- String folderName = null; if (CommonUtil.strNullorEmpty(request.getLocation())) { folderName = "INBOX"; } else { folderName = mapKmrLocationToImapFolder(request.getLocation(), this.host); } msgFolder = (IMAPFolder) sslStore.getFolder(folderName); msgFolder.open(Folder.READ_ONLY); //-------------------------------------------- // Find the message by the given Message-ID //-------------------------------------------- Message msg = this.findMsgByMessageId(msgFolder, request.getMessageId()); if (msg == null) { String errmsg = "Msg NOT FOUND for Message-ID=" + request.getMessageId(); System.out.println("===> getMessageDetail: " + errmsg); response.setSuccessStatus(false); response.setStatusMessage(errmsg); } else { //this.printMsgIdSubject(msg); //DBG printout System.out.println("===> getMessageDetail: Msg FOUND for Message-ID=" + request.getMessageId()); //--------------------------------------------------- // Extract "PATIENTID=" from body if present, so that // user does not see it. //--------------------------------------------------- String content = fetchMsgContent(msg); if (content.startsWith("PATIENTID=")) { Scanner scanner = new Scanner(content); boolean first = true; StringBuilder sb = new StringBuilder(); while (scanner.hasNextLine()) { if (first) { String[] parts = scanner.nextLine().split("="); response.setPatientId(parts[1]); first = false; } else { sb.append(scanner.nextLine()); } } response.getMessageDetail().add(sb.toString()); } else { response.getMessageDetail().add(content); } // Adding patientId coming from the message header. // if (msg.getHeader("X-PATIENTID") != null && // msg.getHeader("X-PATIENTID").length > 0) { // // response.setPatientId(msg.getHeader("X-PATIENT_ID")[0]); // } if (msg.getRecipients(Message.RecipientType.TO) != null) { for (Address a : msg.getRecipients(Message.RecipientType.TO)) { String contactId = getContactIdFromEmail(a.toString()); response.getSentTo().add(contactId); //System.out.println("DisplayMailDataHandler: TO="+ a.toString() +" ldap.cn="+ contactId); } } if (msg.getRecipients(Message.RecipientType.CC) != null) { for (Address a : msg.getRecipients(Message.RecipientType.CC)) { String contactId = getContactIdFromEmail(a.toString()); response.getCCTo().add(contactId); //System.out.println("DisplayMailDataHandler: CC="+ a.toString() +" ldap.cn="+ contactId); } } if (msg.getRecipients(Message.RecipientType.BCC) != null) { for (Address a : msg.getRecipients(Message.RecipientType.BCC)) { String contactId = getContactIdFromEmail(a.toString()); response.getBCCTo().add(contactId); //System.out.println("DisplayMailDataHandler: BCC="+ a.toString() +" ldap.cn="+ contactId); } } response.setSuccessStatus(true); response.setStatusMessage(""); } } catch (Exception e) { response.setSuccessStatus(false); response.setStatusMessage( "Error getting message detail for user: " + access[0] + "\n[EXCEPTION] " + e.toString()); e.printStackTrace(); } finally { if (msgFolder != null) { try { msgFolder.close(false); } catch (Exception e) { } } if (sslStore != null) { try { sslStore.close(); } catch (Exception e) { } } } return response; }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Refresh Information about folders.//from w ww .j ava 2 s . c om * Tries to connect folders that are not yet connected. * * @doCount display message counts for user */ public void refreshFolderInformation(boolean subscribed_only, boolean doCount) { /* Right now, doCount corresponds exactly to subscribed_only. * When we add a user preference setting or one-time action, * to present messages from all folders, we will have * subscribed_only false and doCount true. */ //log.fatal("Invoking refreshFolderInformation(boolean, boolean)", //new Throwable("Thread Dump")); FOR DEBUGGING setEnv(); if (folders == null) folders = new Hashtable<String, Folder>(); Folder rootFolder = null; String cur_mh_id = ""; Enumeration mailhosts = user.mailHosts(); int max_depth = 0; int folderType; while (mailhosts.hasMoreElements()) { cur_mh_id = (String) mailhosts.nextElement(); MailHostData mhd = user.getMailHost(cur_mh_id); URLName url = new URLName(mhd.getHostURL()); Element mailhost = model.createMailhost(mhd.getName(), mhd.getID(), url.toString()); int depth = 0; try { rootFolder = getRootFolder(cur_mh_id); try { rootFolder.setSubscribed(true); } catch (MessagingException ex) { // Only IMAP supports subscription log.warn("Folder.setSubscribed failed. " + "Probably a non-supporting mail service: " + ex); } } catch (MessagingException ex) { mailhost.setAttribute("error", ex.getMessage()); log.warn("Failed to connect and get Root folder from (" + url + ')', ex); return; } try { depth = getFolderTree(rootFolder.getFolder("INBOX"), mailhost, subscribed_only, doCount); log.debug("Loaded INBOX folders below Root to a depth of " + depth); String extraFolderPath = ((imapBasedir == null) ? "~" : imapBasedir) + mhd.getLogin(); //String extraFolderPath = "/home/" + mhd.getLogin(); Folder nonInboxBase = rootFolder.getFolder(extraFolderPath); log.debug("Trying extra base dir " + nonInboxBase.getFullName()); if (nonInboxBase.exists()) { folderType = nonInboxBase.getType(); if ((folderType & Folder.HOLDS_MESSAGES) != 0) { // Can only Subscribe to Folders which may hold Msgs. nonInboxBase.setSubscribed(true); if (!nonInboxBase.isSubscribed()) log.error("A bug in JavaMail or in the server is " + "preventing subscription to '" + nonInboxBase.getFullName() + "' on '" + url + "'. Folders will not be visible."); } int extraDepth = extraDepth = getFolderTree(nonInboxBase, mailhost, subscribed_only, doCount); if (extraDepth > depth) depth = extraDepth; log.debug("Loaded additional folders from below " + nonInboxBase.getFullName() + " with max depth of " + extraDepth); } } catch (Exception ex) { if (!url.getProtocol().startsWith("pop")) mailhost.setAttribute("error", ex.getMessage()); log.warn("Failed to fetch child folders from (" + url + ')', ex); } if (depth > max_depth) max_depth = depth; model.addMailhost(mailhost); } model.setStateVar("max folder depth", (1 + max_depth) + ""); }
From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java
/** * This methog /*from w ww .j av a2 s . c o m*/ * @param message * @param request * @param session * @throws Exception */ private void sendMessagesTOCCBCC(Message[] message, SetMessageRequestType request, Session session) throws Exception { IMAPFolder folder = null; IMAPSSLStore sslStore = null; Set<String> allContacts = new HashSet<String>(); //DBG - Check about CC entry. List<String> ctlist = request.getContactTo(); if (!CommonUtil.listNullorEmpty(ctlist)) { System.out.println("===> TO=" + ctlist.get(0)); } ctlist = request.getContactCC(); if (!CommonUtil.listNullorEmpty(ctlist)) { System.out.println("===> CC=" + ctlist.get(0)); } ctlist = request.getContactBCC(); if (!CommonUtil.listNullorEmpty(ctlist)) { System.out.println("===> BCC=" + ctlist.get(0)); } if (!CommonUtil.listNullorEmpty(request.getContactTo())) { allContacts.addAll(request.getContactTo()); } if (!CommonUtil.listNullorEmpty(request.getContactCC())) { allContacts.addAll(request.getContactCC()); } if (!CommonUtil.listNullorEmpty(request.getContactBCC())) { allContacts.addAll(request.getContactBCC()); } try { for (String ctcName : allContacts) { System.out.println("===> Looking for Contact of given CN=" + ctcName); if (CommonUtil.strNullorEmpty(ctcName)) { continue; } ContactDTO dto = findContactByCn(ctcName); List<String> acctPass = getContactEmailAndPass(dto); String[] access = acctPass.toArray(new String[0]); System.out.println("===> Sending to Contact=" + access[0] + " mapped from given CN=" + ctcName); URLName urlName = new URLName(mailUrl); sslStore = new IMAPSSLStore(session, urlName); sslStore.connect(host, access[0], access[1]); folder = (IMAPFolder) sslStore.getFolder(this.mapKmrLocationToImapFolder("INBOX", this.host)); folder.open(Folder.READ_WRITE); folder.appendMessages(message); folder.close(false); sslStore.close(); } } catch (Exception e) { log.error("Error sending TO, CC and BCC emails: " + e.getMessage()); } 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"); } } } }
From source file:net.wastl.webmail.server.WebMailSession.java
/** Connect to mailhost "name"/*from w w w . ja v a 2s. c o m*/ */ public Folder connect(String name) throws MessagingException { MailHostData m = user.getMailHost(name); URLName url = new URLName(m.getHostURL()); Store st = connectStore(url.getHost(), url.getProtocol(), m.getLogin(), m.getPassword()); Folder f = st.getDefaultFolder(); connections.put(name, f); log.info("Mail: Default folder '" + f.getFullName() + "' retrieved from store " + st + '.'); return f; }