List of usage examples for javax.mail URLName URLName
public URLName(String protocol, String host, int port, String file, String username, String password)
From source file:org.wso2.esb.integration.common.utils.servers.GreenMailServer.java
/** * Get the connection to a mail store//w w w . j ava 2 s . co m * * @param user whose mail store should be connected * @param protocol protocol used to connect * @return * @throws MessagingException when unable to connect to the store */ private static Store getConnection(GreenMailUser user, String protocol) throws MessagingException { Properties props = new Properties(); Session session = Session.getInstance(props); int port; if (PROTOCOL_POP3.equals(protocol)) { port = 3110; } else if (PROTOCOL_IMAP.equals(protocol)) { port = 3143; } else { port = 3025; props.put("mail.smtp.auth", "true"); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", "localhost"); props.put("mail.smtp.port", "3025"); } URLName urlName = new URLName(protocol, BIND_ADDRESS, port, null, user.getLogin(), user.getPassword()); Store store = session.getStore(urlName); store.connect(); return store; }
From source file:com.adaptris.util.URLString.java
/** * Creates a URLString object from the specified protocol, host, port number, file, username, and * password. Specifying a port number of -1 indicates that the URL should use the default port for * the protocol.// w w w . ja v a 2s .c o m */ public URLString(String protocol, String host, int port, String file, String username, String password) { this.protocol = protocol; this.host = host; this.port = port; urlProxy = new URLName(protocol, host, port, file, username, password); this.file = urlProxy.getFile(); this.ref = urlProxy.getRef(); this.username = urlProxy.getUsername(); this.password = urlProxy.getPassword(); this.fullURL = urlProxy.toString(); }
From source file:StoreTreeNode.java
/** * We override toString() so we can display the store URLName * without the password.// w w w.j ava 2 s . c o m */ public String toString() { if (display == null) { URLName url = store.getURLName(); if (url == null) { display = store.toString(); } else { // don't show the password URLName too = new URLName(url.getProtocol(), url.getHost(), url.getPort(), url.getFile(), url.getUsername(), null); display = too.toString(); } } return display; }
From source file:org.webguitoolkit.messagebox.mail.MailChannel.java
/** * // ww w . j av a2 s.c o m */ @Override public List<IMessage> receive(boolean clear) { List<IMessage> result = new ArrayList<IMessage>(); try { String user = properties.getProperty("pop3.login.user"); String password = properties.getProperty("pop3.login.password"); String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties pop3Props = new Properties(); pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false"); pop3Props.setProperty("mail.pop3.port", properties.getProperty("pop3.port")); pop3Props.setProperty("mail.pop3.socketFactory.port", properties.getProperty("pop3.port")); URLName url = new URLName("pop3", properties.getProperty("pop3.host"), Integer.valueOf(properties.getProperty("pop3.port")), "", user, password); Session session = Session.getInstance(pop3Props, null); Store store = new POP3SSLStore(session, url); store.connect(); // Open the Folder Folder folder = store.getDefaultFolder(); folder = folder.getFolder("INBOX"); if (folder == null) { throw new RuntimeException("Invalid folder INBOX"); } // try to open read/write and if that fails try read-only try { folder.open(Folder.READ_WRITE); } catch (MessagingException ex) { folder.open(Folder.READ_ONLY); } int count = folder.getMessageCount(); // Message numbers start at 1 for (int i = 1; i <= count; i++) { // Get a message by its sequence number Message m = folder.getMessage(i); Address[] from = m.getFrom(); String type = from[0].getType(); IMessage message = new MailMessage(from[0].toString(), this, m.getSubject(), getContent(m)); result.add(message); // delete message ? if (clear) m.setFlag(Flags.Flag.DELETED, true); } // "true" actually deletes flagged messages from folder folder.close(clear); store.close(); } catch (Exception e) { throw new RuntimeException(e); } return result; }
From source file:org.apache.axis2.transport.mail.SimpleMailListener.java
public void init(ConfigurationContext configurationContext, TransportInDescription transportIn) throws AxisFault { this.configurationContext = configurationContext; ArrayList mailParameters = transportIn.getParameters(); String password = ""; String host = ""; String protocol = ""; String port = ""; URLName urlName;/*w w w .j a v a 2 s . co m*/ for (Iterator iterator = mailParameters.iterator(); iterator.hasNext();) { Parameter param = (Parameter) iterator.next(); String paramKey = param.getName(); String paramValue = Utils.getParameterValue(param); if (paramKey == null || paramValue == null) { String error = Messages.getMessage("canNotBeNull", "Parameter name and value"); log.error(error); throw new AxisFault(error); } pop3Properties.setProperty(paramKey, paramValue); if (paramKey.equals(org.apache.axis2.transport.mail.Constants.POP3_USER)) { user = paramValue; } if (paramKey.equals(org.apache.axis2.transport.mail.Constants.POP3_PASSWORD)) { password = paramValue; } if (paramKey.equals(org.apache.axis2.transport.mail.Constants.POP3_HOST)) { host = paramValue; } if (paramKey.equals(org.apache.axis2.transport.mail.Constants.STORE_PROTOCOL)) { protocol = paramValue; } if (paramKey.equals(org.apache.axis2.transport.mail.Constants.POP3_PORT)) { port = paramValue; } //Transport specific if (paramKey.equals(org.apache.axis2.transport.mail.Constants.REPLY_TO)) { replyTo = paramValue; } if (paramKey.equals(org.apache.axis2.transport.mail.Constants.LISTENER_INTERVAL)) { listenerWaitInterval = Integer.parseInt(paramValue); } } if (password.length() == 0 || user.length() == 0 || host.length() == 0 || protocol.length() == 0) { String error = SimpleMailListener.class.getName() + " one or more of Password, User, Host and Protocol are null or empty"; log.error(error); throw new AxisFault(error); } if (port.length() == 0) { urlName = new URLName(protocol, host, -1, "", user, password); } else { urlName = new URLName(protocol, host, Integer.parseInt(port), "", user, password); } receiver.setPop3Properties(pop3Properties); receiver.setUrlName(urlName); Object obj = configurationContext.getProperty(org.apache.axis2.transport.mail.Constants.MAPPING_TABLE); if (obj == null) { configurationContext.setProperty(org.apache.axis2.transport.mail.Constants.MAPPING_TABLE, new Hashtable()); } Object callBackTable = configurationContext .getProperty(org.apache.axis2.transport.mail.Constants.CALLBACK_TABLE); if (callBackTable == null) { configurationContext.setProperty(org.apache.axis2.transport.mail.Constants.CALLBACK_TABLE, new Hashtable()); } }
From source file:org.apache.axis2.transport.mail.SimpleMailListener.java
public void initFromRuntime(Properties properties, MessageContext msgContext) throws AxisFault { this.configurationContext = msgContext.getConfigurationContext(); String password = ""; String host = ""; String protocol = ""; String port = ""; URLName urlName;/*w w w. j a v a 2 s. c o m*/ pop3Properties.clear(); pop3Properties.putAll(properties); user = properties.getProperty(org.apache.axis2.transport.mail.Constants.POP3_USER); password = properties.getProperty(org.apache.axis2.transport.mail.Constants.POP3_PASSWORD); host = properties.getProperty(org.apache.axis2.transport.mail.Constants.POP3_HOST); protocol = properties.getProperty(org.apache.axis2.transport.mail.Constants.STORE_PROTOCOL); port = properties.getProperty(org.apache.axis2.transport.mail.Constants.POP3_PORT); replyTo = properties.getProperty(org.apache.axis2.transport.mail.Constants.REPLY_TO); String value = properties.getProperty(org.apache.axis2.transport.mail.Constants.LISTENER_INTERVAL); if (value != null) { listenerWaitInterval = Integer.parseInt(value); } if (password.length() == 0 || user.length() == 0 || host.length() == 0 || protocol.length() == 0) { String error = SimpleMailListener.class.getName() + " one or more of Password, User," + " Host and Protocol are null or empty" + "in runtime settings"; log.error(error); throw new AxisFault(error); } if (port == null) { urlName = new URLName(protocol, host, -1, "", user, password); } else { urlName = new URLName(protocol, host, Integer.parseInt(port), "", user, password); } receiver.setPop3Properties(pop3Properties); receiver.setUrlName(urlName); Object obj = configurationContext.getProperty(org.apache.axis2.transport.mail.Constants.MAPPING_TABLE); if (obj == null) { configurationContext.setProperty(org.apache.axis2.transport.mail.Constants.MAPPING_TABLE, new Hashtable()); } Object callBackTable = configurationContext .getProperty(org.apache.axis2.transport.mail.Constants.CALLBACK_TABLE); if (callBackTable == null) { configurationContext.setProperty(org.apache.axis2.transport.mail.Constants.CALLBACK_TABLE, new Hashtable()); } }
From source file:org.pentaho.di.job.entries.getpop.MailConnection.java
/** * Construct a new Database MailConnection * * @param protocol/* w ww . ja v a 2 s. co m*/ * the protocol used : MailConnection.PROTOCOL_POP3 or MailConnection.PROTOCOL_IMAP. * @param server * the target server (ip ou name) * @param port * port number on the server * @param password * @param usessl * specify if the connection is established via SSL * @param useproxy * specify if we use proxy authentication * @param proxyusername * proxy authorised user */ public MailConnection(LogChannelInterface log, int protocol, String server, int port, String username, String password, boolean usessl, boolean useproxy, String proxyusername) throws KettleException { this.log = log; // Get system properties try { this.prop = System.getProperties(); } catch (SecurityException s) { this.prop = new Properties(); } this.port = port; this.server = server; this.username = username; this.password = password; this.usessl = usessl; this.protocol = protocol; this.nrSavedMessages = 0; this.nrDeletedMessages = 0; this.nrMovedMessages = 0; this.nrSavedAttachedFiles = 0; this.messagenr = -1; this.useproxy = useproxy; this.proxyusername = proxyusername; try { if (useproxy) { // Need here to pass a proxy // use SASL authentication this.prop.put("mail.imap.sasl.enable", "true"); this.prop.put("mail.imap.sasl.authorizationid", proxyusername); } if (protocol == MailConnectionMeta.PROTOCOL_POP3) { this.prop.setProperty("mail.pop3s.rsetbeforequit", "true"); this.prop.setProperty("mail.pop3.rsetbeforequit", "true"); } else if (protocol == MailConnectionMeta.PROTOCOL_MBOX) { this.prop.setProperty("mstor.mbox.metadataStrategy", "none"); // mstor.mbox.metadataStrategy={none|xml|yaml} this.prop.setProperty("mstor.cache.disabled", "true"); // prevent diskstore fail } String protocolString = (protocol == MailConnectionMeta.PROTOCOL_POP3) ? "pop3" : protocol == MailConnectionMeta.PROTOCOL_MBOX ? "mstor" : "imap"; if (usessl && protocol != MailConnectionMeta.PROTOCOL_MBOX) { // Supports IMAP/POP3 connection with SSL, the connection is established via SSL. this.prop.setProperty("mail." + protocolString + ".socketFactory.class", "javax.net.ssl.SSLSocketFactory"); this.prop.setProperty("mail." + protocolString + ".socketFactory.fallback", "false"); this.prop.setProperty("mail." + protocolString + ".port", "" + port); this.prop.setProperty("mail." + protocolString + ".socketFactory.port", "" + port); // Create session object this.session = Session.getInstance(this.prop, null); this.session.setDebug(log.isDebug()); if (this.port == -1) { this.port = ((protocol == MailConnectionMeta.PROTOCOL_POP3) ? MailConnectionMeta.DEFAULT_SSL_POP3_PORT : MailConnectionMeta.DEFAULT_SSL_IMAP_PORT); } URLName url = new URLName(protocolString, server, port, "", username, password); this.store = (protocol == MailConnectionMeta.PROTOCOL_POP3) ? new POP3SSLStore(this.session, url) : new IMAPSSLStore(this.session, url); url = null; } else { this.session = Session.getInstance(this.prop, null); this.session.setDebug(log.isDebug()); if (protocol == MailConnectionMeta.PROTOCOL_MBOX) { this.store = this.session.getStore(new URLName(protocolString + ":" + server)); } else { this.store = this.session.getStore(protocolString); } } if (log.isDetailed()) { log.logDetailed(BaseMessages.getString(PKG, "JobGetMailsFromPOP.NewConnectionDefined")); } } catch (Exception e) { throw new KettleException(BaseMessages.getString(PKG, "JobGetMailsFromPOP.Error.NewConnection", Const.NVL(this.server, "")), e); } }
From source file:com.cws.esolutions.core.utils.EmailUtils.java
/** * Processes and sends an email message as generated by the requesting * application. This method is utilized with a JNDI datasource. * * @param dataSource - The email message * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise * @param authList - If authRequired is true, this must be populated with the auth info * @return List - The list of email messages in the mailstore * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing *///from w w w . j a v a 2s.c o m public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException { final String methodName = EmailUtils.CNAME + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("dataSource: {}", dataSource); DEBUGGER.debug("authRequired: {}", authRequired); DEBUGGER.debug("authList: {}", authList); } Folder mailFolder = null; Session mailSession = null; Folder archiveFolder = null; List<EmailMessage> emailMessages = null; Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, -24); final Long TIME_PERIOD = cal.getTimeInMillis(); final URLName URL_NAME = (authRequired) ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1)) : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, null, null); if (DEBUG) { DEBUGGER.debug("timePeriod: {}", TIME_PERIOD); DEBUGGER.debug("URL_NAME: {}", URL_NAME); } try { // Set up mail session mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator()) : Session.getDefaultInstance(dataSource); if (DEBUG) { DEBUGGER.debug("mailSession: {}", mailSession); } if (mailSession == null) { throw new MessagingException("Unable to configure email services"); } mailSession.setDebug(DEBUG); Store mailStore = mailSession.getStore(URL_NAME); mailStore.connect(); if (DEBUG) { DEBUGGER.debug("mailStore: {}", mailStore); } if (!(mailStore.isConnected())) { throw new MessagingException("Failed to connect to mail service. Cannot continue."); } mailFolder = mailStore.getFolder("inbox"); archiveFolder = mailStore.getFolder("archive"); if (!(mailFolder.exists())) { throw new MessagingException("Requested folder does not exist. Cannot continue."); } mailFolder.open(Folder.READ_WRITE); if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) { throw new MessagingException("Failed to open requested folder. Cannot continue"); } if (!(archiveFolder.exists())) { archiveFolder.create(Folder.HOLDS_MESSAGES); } Message[] mailMessages = mailFolder.getMessages(); if (mailMessages.length == 0) { throw new MessagingException("No messages were found in the provided store."); } emailMessages = new ArrayList<EmailMessage>(); for (Message message : mailMessages) { if (DEBUG) { DEBUGGER.debug("MailMessage: {}", message); } // validate the message here String messageId = message.getHeader("Message-ID")[0]; Long messageDate = message.getReceivedDate().getTime(); if (DEBUG) { DEBUGGER.debug("messageId: {}", messageId); DEBUGGER.debug("messageDate: {}", messageDate); } // only get emails for the last 24 hours // this should prevent us from pulling too // many emails if (messageDate >= TIME_PERIOD) { // process it Multipart attachment = (Multipart) message.getContent(); Map<String, InputStream> attachmentList = new HashMap<String, InputStream>(); for (int x = 0; x < attachment.getCount(); x++) { BodyPart bodyPart = attachment.getBodyPart(x); if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) { continue; } attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream()); } List<String> toList = new ArrayList<String>(); List<String> ccList = new ArrayList<String>(); List<String> bccList = new ArrayList<String>(); List<String> fromList = new ArrayList<String>(); for (Address from : message.getFrom()) { fromList.add(from.toString()); } if ((message.getRecipients(RecipientType.TO) != null) && (message.getRecipients(RecipientType.TO).length != 0)) { for (Address to : message.getRecipients(RecipientType.TO)) { toList.add(to.toString()); } } if ((message.getRecipients(RecipientType.CC) != null) && (message.getRecipients(RecipientType.CC).length != 0)) { for (Address cc : message.getRecipients(RecipientType.CC)) { ccList.add(cc.toString()); } } if ((message.getRecipients(RecipientType.BCC) != null) && (message.getRecipients(RecipientType.BCC).length != 0)) { for (Address bcc : message.getRecipients(RecipientType.BCC)) { bccList.add(bcc.toString()); } } EmailMessage emailMessage = new EmailMessage(); emailMessage.setMessageTo(toList); emailMessage.setMessageCC(ccList); emailMessage.setMessageBCC(bccList); emailMessage.setEmailAddr(fromList); emailMessage.setMessageAttachments(attachmentList); emailMessage.setMessageDate(message.getSentDate()); emailMessage.setMessageSubject(message.getSubject()); emailMessage.setMessageBody(message.getContent().toString()); emailMessage.setMessageSources(message.getHeader("Received")); if (DEBUG) { DEBUGGER.debug("emailMessage: {}", emailMessage); } emailMessages.add(emailMessage); if (DEBUG) { DEBUGGER.debug("emailMessages: {}", emailMessages); } } // archive it archiveFolder.open(Folder.READ_WRITE); if (archiveFolder.isOpen()) { mailFolder.copyMessages(new Message[] { message }, archiveFolder); message.setFlag(Flags.Flag.DELETED, true); } } } catch (IOException iox) { throw new MessagingException(iox.getMessage(), iox); } catch (MessagingException mex) { throw new MessagingException(mex.getMessage(), mex); } finally { try { if ((mailFolder != null) && (mailFolder.isOpen())) { mailFolder.close(true); } if ((archiveFolder != null) && (archiveFolder.isOpen())) { archiveFolder.close(false); } } catch (MessagingException mx) { ERROR_RECORDER.error(mx.getMessage(), mx); } } return emailMessages; }
From source file:be.ibridge.kettle.job.entry.getpop.JobEntryGetPOP.java
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = new Result(nr); result.setResult(false);//from w w w . j av a 2s.com result.setNrErrors(1); FileObject fileObject = null; //Get system properties //Properties prop = System.getProperties(); Properties prop = new Properties(); //Create session object //Session sess = Session.getDefaultInstance(prop,null); Session sess = Session.getInstance(prop, null); sess.setDebug(true); try { int nbrmailtoretrieve = Const.toInt(firstmails, 0); fileObject = KettleVFS.getFileObject(getRealOutputDirectory()); // Check if output folder exists if (!fileObject.exists()) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.FolderNotExists1.Label") + getRealOutputDirectory() + Messages.getString("JobGetMailsFromPOP.FolderNotExists2.Label")); } else { String host = getRealServername(); String user = getRealUsername(); String pwd = getRealPassword(); Store st = null; if (!getUseSSL()) { //Create POP3 object st = sess.getStore("pop3"); // Try to connect to the server st.connect(host, user, pwd); } else { // Ssupports POP3 connection with SSL, the connection is established via SSL. String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //Properties pop3Props = new Properties(); prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); prop.setProperty("mail.pop3.socketFactory.fallback", "false"); prop.setProperty("mail.pop3.port", getRealSSLPort()); prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); st = new POP3SSLStore(sess, url); st.connect(); } log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //Open default folder INBOX Folder f = st.getFolder("INBOX"); f.open(Folder.READ_ONLY); if (f == null) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); } else { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder1.Label") + f.getName() + Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder2.Label") + f.getMessageCount()); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder1.Label") + f.getName() + Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder2.Label") + f.getNewMessageCount()); // Get emails Message msg_list[] = getPOPMessages(f, retrievemails); if (msg_list.length > 0) { List current_file_POP = new ArrayList(); List current_filepath_POP = new ArrayList(); int nb_email_POP = 1; DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy"); String startpattern = "name"; if (!Const.isEmpty(getRealFilenamePattern())) { startpattern = getRealFilenamePattern(); } for (int i = 0; i < msg_list.length; i++) { /*if(msg[i].isMimeType("text/plain")) { log.logDetailed(toString(), "Expediteur: "+msg[i].getFrom()[0]); log.logDetailed(toString(), "Sujet: "+msg[i].getSubject()); log.logDetailed(toString(), "Texte: "+(String)msg[i].getContent()); }*/ if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) { Message msg_POP = msg_list[i]; log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label") + msg_list[i].getFrom()[0]); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailSubject.Label") + msg_list[i].getSubject()); String localfilename_message = startpattern + "_" + dateFormat.format(new Date()) + "_" + (i + 1) + ".mail"; log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LocalFilename1.Label") + localfilename_message + Messages.getString("JobGetMailsFromPOP.LocalFilename2.Label")); File filename_message = new File(getRealOutputDirectory(), localfilename_message); OutputStream os_filename = new FileOutputStream(filename_message); Enumeration enums_POP = msg_POP.getAllHeaders(); while (enums_POP.hasMoreElements()) { Header header_POP = (Header) enums_POP.nextElement(); os_filename.write(new StringBuffer(header_POP.getName()).append(": ") .append(header_POP.getValue()).append("\r\n").toString().getBytes()); } os_filename.write("\r\n".getBytes()); InputStream in_POP = msg_POP.getInputStream(); byte[] buffer_POP = new byte[1024]; int length_POP = 0; while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) { os_filename.write(buffer_POP, 0, length_POP); } os_filename.close(); nb_email_POP++; current_file_POP.add(filename_message); current_filepath_POP.add(filename_message.getPath()); if (delete) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true); } } } } // Close and exit if (f != null) f.close(false); if (st != null) st.close(); f = null; st = null; sess = null; result.setNrErrors(0); result.setResult(true); } } } catch (NoSuchProviderException e) { log.logError(toString(), "provider error: " + e.getMessage()); } catch (MessagingException e) { log.logError(toString(), "Message error: " + e.getMessage()); } catch (Exception e) { log.logError(toString(), "Inexpected error: " + e.getMessage()); } finally { if (fileObject != null) { try { fileObject.close(); } catch (IOException ex) { } ; } sess = null; } return result; }
From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java
@SuppressWarnings({ "unchecked" }) public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = previousResult; result.setResult(false);//from ww w .ja va 2 s .c o m result.setNrErrors(1); //Get system properties Properties prop = new Properties(); prop.setProperty("mail.pop3s.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$ prop.setProperty("mail.pop3.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$ //Create session object Session sess = Session.getDefaultInstance(prop, null); sess.setDebug(true); FileObject fileObject = null; Store st = null; Folder f = null; try { int nbrmailtoretrieve = Const.toInt(firstmails, 0); String realOutputFolder = getRealOutputDirectory(); fileObject = KettleVFS.getFileObject(realOutputFolder); // Check if output folder exists if (!fileObject.exists()) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.FolderNotExists.Label", realOutputFolder)); //$NON-NLS-1$ } else { if (fileObject.getType() == FileType.FOLDER) { String host = getRealServername(); String user = getRealUsername(); String pwd = getRealPassword(); if (!getUseSSL()) { //Create POP3 object st = sess.getStore("pop3"); //$NON-NLS-1$ // Try to connect to the server st.connect(host, user, pwd); } else { // Ssupports POP3 connection with SSL, the connection is established via SSL. String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.fallback", "false"); //$NON-NLS-1$ //$NON-NLS-2$ prop.setProperty("mail.pop3.port", getRealSSLPort()); //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); //$NON-NLS-1$ URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); //$NON-NLS-1$ //$NON-NLS-2$ st = new POP3SSLStore(sess, url); st.connect(); } if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //$NON-NLS-1$ //Open the INBOX FOLDER // For POP3, the only folder available is the INBOX. f = st.getFolder("INBOX"); //$NON-NLS-1$ if (f == null) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); //$NON-NLS-1$ } else { // Open folder if (delete) f.open(Folder.READ_WRITE); else f.open(Folder.READ_ONLY); Message messageList[] = f.getMessages(); if (log.isDetailed()) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder.Label", f.getName(), //$NON-NLS-1$ String.valueOf(messageList.length))); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalUnreadMessagesFolder.Label", //$NON-NLS-1$ f.getName(), String.valueOf(f.getUnreadMessageCount()))); } // Get emails Message msg_list[] = getPOPMessages(f, retrievemails); if (msg_list.length > 0) { List<File> current_file_POP = new ArrayList<File>(); List<String> current_filepath_POP = new ArrayList<String>(); int nb_email_POP = 1; String startpattern = "name"; //$NON-NLS-1$ if (!Const.isEmpty(getRealFilenamePattern())) { startpattern = getRealFilenamePattern(); } for (int i = 0; i < msg_list.length; i++) { if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) { Message msg_POP = msg_list[i]; if (log.isDetailed()) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label", //$NON-NLS-1$ msg_list[i].getFrom()[0].toString())); log.logDetailed(toString(), Messages.getString( "JobGetMailsFromPOP.EmailSubject.Label", msg_list[i].getSubject())); //$NON-NLS-1$ } String localfilename_message = startpattern + "_" //$NON-NLS-1$ + StringUtil.getFormattedDateTimeNow(true) + "_" + (i + 1) + ".mail"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDetailed()) log.logDetailed(toString(), Messages.getString( "JobGetMailsFromPOP.LocalFilename.Label", localfilename_message)); //$NON-NLS-1$ File filename_message = new File(realOutputFolder, localfilename_message); OutputStream os_filename = new FileOutputStream(filename_message); Enumeration<Header> enums_POP = msg_POP.getAllHeaders(); while (enums_POP.hasMoreElements()) { Header header_POP = enums_POP.nextElement(); os_filename.write(new StringBuffer(header_POP.getName()).append(": ") //$NON-NLS-1$ .append(header_POP.getValue()).append("\r\n").toString().getBytes()); //$NON-NLS-1$ } os_filename.write("\r\n".getBytes()); //$NON-NLS-1$ InputStream in_POP = msg_POP.getInputStream(); byte[] buffer_POP = new byte[1024]; int length_POP = 0; while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) { os_filename.write(buffer_POP, 0, length_POP); } os_filename.close(); nb_email_POP++; current_file_POP.add(filename_message); current_filepath_POP.add(filename_message.getPath()); // Check attachments Object content = msg_POP.getContent(); if (content instanceof Multipart) { handleMultipart(realOutputFolder, (Multipart) content); } // Check if mail has to be deleted if (delete) { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); //$NON-NLS-1$ msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true); } } } } result.setNrErrors(0); result.setResult(true); } } else { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.Error.NotAFolder", realOutputFolder)); } } } catch (NoSuchProviderException e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.ProviderException", e.getMessage())); //$NON-NLS-1$ } catch (MessagingException e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.MessagingException", e.getMessage())); //$NON-NLS-1$ } catch (Exception e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.GeneralException", e.getMessage())); //$NON-NLS-1$ } finally { if (fileObject != null) { try { fileObject.close(); } catch (IOException ex) { } ; } //close the folder, passing in a true value to expunge the deleted message try { if (f != null) f.close(true); if (st != null) st.close(); } catch (Exception e) { log.logError(toString(), e.getMessage()); } // free memory f = null; st = null; sess = null; } return result; }