@Override public void connect() { Properties properties = new Properties(); try { int port = configuration.getPort(); String portS = String.valueOf(port); properties.setProperty("mail.store.protocol", "pop3"); properties.setProperty("mail.pop3.port", portS); properties.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.setProperty("mail.pop3.socketFactory.fallback", "true"); properties.setProperty("mail.pop3.port", portS); properties.setProperty("mail.pop3.socketFactory.port", portS); URLName url = new URLName("pop3s", configuration.getServer(), port, "", configuration.getUsername(), configuration.getPassword()); Session session = Session.getInstance(properties, null); store = session.getStore(url); store.connect(); folder = store.getFolder(configuration.getFolderName()); folder.open(Folder.READ_WRITE); } catch (MessagingException e) { LOGGER.error("error - cannot connect to mail server", e); throw new ConnectorException(e); } }
/** * Get the connection to a mail store * * @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; }
public Store connectWithPOP3SSL(BatchClassEmailConfiguration configuration) throws MessagingException { Properties pop3Props = new Properties(); pop3Props.setProperty("mail.pop3.socketFactory.class", MailConstants.SSL_FACTORY); pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false"); Integer portNumber = configuration.getPortNumber(); if (portNumber == null) { LOGGER.error("Could not find port number. Trying with default value of 995"); portNumber = MailConstants.DEFAULT_PORT_NUMBER_POP3; } URLName url = new URLName(configuration.getServerType(), configuration.getServerName(), portNumber, "", configuration .getUserName(), configuration.getPassword()); session = Session.getInstance(pop3Props, null); store = new POP3SSLStore(session, url); store.connect(); return store; }
public Store connectWithIMAPSSL(BatchClassEmailConfiguration configuration) throws MessagingException { Properties imapProps = new Properties(); imapProps.setProperty("mail.imap.socketFactory.class", MailConstants.SSL_FACTORY); imapProps.setProperty("mail.imap.socketFactory.fallback", "false"); imapProps.setProperty("mail.imap.partialfetch", "false"); Integer portNumber = configuration.getPortNumber(); if (portNumber == null) { LOGGER.error("Could not find port number. Trying with default value of 993"); portNumber = MailConstants.DEFAULT_PORT_NUMBER_IMAP; } URLName url = new URLName(configuration.getServerType(), configuration.getServerName(), portNumber, "", configuration .getUserName(), configuration.getPassword()); session = Session.getInstance(imapProps, null); store = new IMAPSSLStore(session, url); store.connect(); return store; }
/** * API to connect to the email configuration with POP3 server type. * * @param emailConfigData {@link EmailConfigurationData} * @return * @throws MessagingException {@link MessagingException} * @throws AuthenticationFailedException {@link AuthenticationFailedException} */ public static Store connectWithPOP3SSL(final EmailConfigurationData emailConfigData) throws MessagingException, AuthenticationFailedException { LOGGER.info("Entering method connectWithPOP3SSL..."); Properties pop3Props = new Properties(); pop3Props.setProperty("mail.pop3.socketFactory.class", IUtilCommonConstants.SSL_FACTORY); pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false"); Integer portNumber = emailConfigData.getPortNumber(); LOGGER.debug("Port Number :: " + portNumber); if (portNumber == null) { LOGGER.error("Could not find port number. Trying with default value of 995"); throw new MessagingException("Could not connect to port number " + portNumber + ". Try connecting with defualt port number " + IUtilCommonConstants.DEFAULT_PORT_NUMBER_POP3 + " for pop3 and " + IUtilCommonConstants.DEFAULT_PORT_NUMBER_IMAP + " for IMAP "); } URLName url = new URLName(emailConfigData.getServerType(), emailConfigData.getServerName(), portNumber, "", emailConfigData .getUserName(), emailConfigData.getPassword()); Session session = Session.getInstance(pop3Props, null); Store store = new POP3SSLStore(session, url); store.connect(); LOGGER.info("Exiting method connectWithPOP3SSL..."); return store; }
public JavaxMailStorage get() throws MessagingException { Properties properties = new Properties(); properties.setProperty("mail.store.protocol", "mstor"); properties.setProperty("mstor.mbox.metadataStrategy", "none"); properties.setProperty("mstor.mbox.cacheBuffers", "disabled"); properties.setProperty("mstor.mbox.bufferStrategy", "mapped"); properties.setProperty("mstor.metadata", "disabled"); properties.setProperty("mstor.mozillaCompatibility", "enabled"); Session session = Session.getDefaultInstance(properties); // /Users/flan/Desktop/Copy of Marie's Mail/Mail/Mail/mail.lean.to File mailbox = new File(commandLineArguments.mailboxFileName); if (!mailbox.exists()) { throw new MessagingException("No such mailbox:" + mailbox); } Store store = session.getStore( new URLName("mstor:" + mailbox.getAbsolutePath())); store.connect(); return new ThunderbirdMailStorage( logger, new JavaxMailFolder(store.getDefaultFolder()), statusParser); }
@Before public void setUp() throws MessagingException, IOException { Properties properties = new Properties(); properties.put("mail.files.path", "target" + File.separatorChar + "output"); Session session = Session.getDefaultInstance(properties); transport = new AbstractFileTransport(session, new URLName("AbstractFileDev")) { @Override protected void writeMessage(Message message, OutputStream os) throws IOException, MessagingException { // do nothing } @Override protected String getFilenameExtension() { return BASE_EXT; } }; cleanup(); }
@Before public void setUp() throws Exception { System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestContextFactory.class.getName()); QueueConnectionFactory queueConnectionFactory = Mockito.mock(QueueConnectionFactory.class); Queue queue = Mockito.mock(Queue.class); Context context = Mockito.mock(Context.class); TestContextFactory.context = context; when(context.lookup(eq("jms/queueConnectionFactory"))).thenReturn(queueConnectionFactory); when(context.lookup(eq("jms/mailQueue"))).thenReturn(queue); queueSender = Mockito.mock(QueueSender.class); QueueConnection queueConnection = Mockito.mock(QueueConnection.class); when(queueConnectionFactory.createQueueConnection()).thenReturn(queueConnection); when(queueConnectionFactory.createQueueConnection(anyString(), anyString())).thenReturn(queueConnection); QueueSession queueSession = Mockito.mock(QueueSession.class); bytesMessage = Mockito.mock(BytesMessage.class); when(queueSession.createBytesMessage()).thenReturn(bytesMessage); when(queueConnection.createQueueSession(anyBoolean(), anyInt())).thenReturn(queueSession); when(queueSession.createSender(eq(queue))).thenReturn(queueSender); transport = new SmtpJmsTransport(Session.getDefaultInstance(new Properties()), new URLName("jms")); transportListener = Mockito.mock(TransportListener.class); transport.addTransportListener(transportListener); }
private SMTPTransport connectToSmtp(String host, int port, String userEmail, String oauthToken, boolean debug) throws MessagingException { Properties props = new Properties(); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.starttls.required", "true"); props.put("mail.smtp.sasl.enable", "false"); props.put("mail.smtp.ssl.enable", true); session = Session.getInstance(props); session.setDebug(debug); final URLName unusedUrlName = null; SMTPTransport transport = new SMTPTransport(session, unusedUrlName); // If the password is non-null, SMTP tries to do AUTH LOGIN. final String emptyPassword = null; transport.connect(host, port, userEmail, emptyPassword); byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", userEmail, oauthToken).getBytes(); response = BASE64EncoderStream.encode(response); transport.issueCommand("AUTH XOAUTH2 " + new String(response), 235); return transport; }
private void importMails(GlobalUser user) throws MessagingException { logger.debug("Importing mail for " + user.getUsernameObject()); Properties properties = new Properties(); Session session = Session.getInstance(properties); Store store = session.getStore(new URLName("pop3://" + user.getUsernameObject() + ":" + user.getPassword() + "@" + remoteHost + ":" + +remotePort + "/INBOX")); store.connect(); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); Message[] messages = folder.getMessages(); int cSuccessfulMails = 0; // user name currently equals with the maildrop name, but this is // not necessarily true in general. String maildropName = user.getUsernameObject().toString(); for (Message message : messages) { try { importMail(maildropName, message); message.setFlag(Flags.Flag.DELETED, true); cSuccessfulMails++; } catch (Exception e) { logger.error("Importing a mail for " + user.getUsernameObject() + " failed", e); } } folder.close(true); store.close(); totalMailCount += cSuccessfulMails; if (cSuccessfulMails > 0) totalUsersWithAtLeastOneMail++; logger.debug(cSuccessfulMails + " mails were imported for " + user.getUsernameObject()); }
public SMTPTransport connectToSmtp(String userEmail, String oauthToken, Session session) throws Exception { final URLName unusedUrlName = null; SMTPTransport transport = new SMTPTransport(session, unusedUrlName); final String emptyPassword = null; final String host = "smtp.gmail.com"; final int port = 587; transport.connect(host, port, userEmail, emptyPassword); byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", userEmail, oauthToken).getBytes(); response = BASE64EncoderStream.encode(response); transport.issueCommand("AUTH XOAUTH2 " + new String(response), 235); return transport; }
@Test public void testConfigureStoreWithTLS() throws Exception { doReturn(objectMock).when(propertiesMock).setProperty("mail." + POP3_PROTOCOL + ".ssl.enable", STR_FALSE); doReturn(objectMock).when(propertiesMock).setProperty("mail." + POP3_PROTOCOL + ".starttls.enable", STR_TRUE); doReturn(objectMock).when(propertiesMock).setProperty("mail." + POP3_PROTOCOL + ".starttls.required", STR_TRUE); PowerMockito.whenNew(URLName.class) .withArguments(anyString(), anyString(), anyInt(), anyString(), anyString(), anyString()) .thenReturn(urlNameMock); PowerMockito.mockStatic(Session.class); PowerMockito.doReturn(sessionMock) .when(Session.class, "getInstance", Matchers.<Properties>any(), Matchers.<Authenticator>any()); doReturn(storeMock).when(sessionMock).getStore(any(String.class)); addRequiredInputs(); getMailMessageSpy.processInputs(inputs); Store store = getMailMessageSpy.configureStoreWithTLS(propertiesMock, authenticatorMock); assertEquals(storeMock, store); verify(propertiesMock).setProperty("mail." + POP3_PROTOCOL + ".ssl.enable", STR_FALSE); verify(propertiesMock).setProperty("mail." + POP3_PROTOCOL + ".starttls.enable", STR_TRUE); verify(propertiesMock).setProperty("mail." + POP3_PROTOCOL + ".starttls.required", STR_TRUE); PowerMockito.verifyStatic(); Session.getInstance(Matchers.<Properties>any(), Matchers.<Authenticator>any()); verify(sessionMock).getStore(POP3_PROTOCOL + SECURE_SUFFIX_FOR_POP3_AND_IMAP); }
@Test public void mailSenderEmpty() throws IOException, MessagingException { Socket smtpSocket; String hostAddress = greenMail.getSmtp().getBindTo(); int port = greenMail.getSmtp().getPort(); Session smtpSession = greenMail.getSmtp().createSession(); URLName smtpURL = new URLName(hostAddress); SMTPTransport smtpTransport = new SMTPTransport(smtpSession, smtpURL); try { smtpSocket = new Socket(hostAddress, port); smtpTransport.connect(smtpSocket); assertThat(smtpTransport.isConnected(),is(equalTo(true))); smtpTransport.issueCommand("MAIL FROM: <>", -1); assertThat("250 OK", equalToIgnoringWhiteSpace(smtpTransport.getLastServerResponse())); } finally { smtpTransport.close(); } }
private Folder getInboxFolder () throws MessagingException { Properties pop3Props = new Properties(); pop3Props.setProperty("mail.pop3.host", host); Authenticator auth = new PopupAuthenticator(); Session session = Session.getInstance(pop3Props, auth); URLName url = new URLName("pop3", host, port, "", username, password); Store store = session.getStore(url); store.connect(); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); return folder; }
private SMTPTransport connectToSmtp(Session session, String host, int port, String userEmail, String oauthToken) throws MessagingException { final URLName unusedUrlName = null; SMTPTransport transport = new SMTPTransport(session, unusedUrlName); // If the password is non-null, SMTP tries to do AUTH LOGIN. final String emptyPassword = null; transport.connect(host, port, userEmail, emptyPassword); byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", userEmail, oauthToken).getBytes(); response = BASE64EncoderStream.encode(response); transport.issueCommand("AUTH XOAUTH2 " + new String(response), 235); return transport; }
/** * Opens a connection to a mail server * * @param url URL in the format </code>protocol://user[:password]@server[:port]</code> * @return Mail Store for the connection * @throws MessagingException */ private Store openConnection(String url) throws MessagingException { URLName urlName = new URLName(url); log.debug("opening " + urlName.getProtocol() + " conection to " + urlName.getHost()); Properties props = new Properties(); Session session = Session.getDefaultInstance(props); Store store = session.getStore(urlName); store.connect(); return store; }
public static void main(String[] args) throws Exception { Properties props = System.getProperties(); props.put("mail.smtp.host", "smtp.163.com"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, null); URLName urln = new URLName("pop3", "pop3.163.com", 110, null, "wang8763710", "wang3864995"); Store store = session.getStore(urln); try { store.connect(); } catch (Exception e) { throw new RuntimeException("connection exception : " + e.getMessage()); } Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages(); System.out.println("Messages's length: " + message.length + "\n"); MailReceiver mailReceiver = null; for(int i = 0; i < message.length; i++ ) { mailReceiver = new MailReceiver((MimeMessage) message[i]); System.out.println("Message " + i + " subject: " + mailReceiver.getSubject()); System.out.println("Message " + i + " sentdate: "+ mailReceiver.getSentDate()); System.out.println("Message " + i + " replysign: "+ mailReceiver.getReplySign()); System.out.println("Message " + i + " hasRead: " + mailReceiver.isNew()); System.out.println("Message " + i + " containAttachment: "+ mailReceiver.isContainAttach((Part) message[i])); System.out.println("Message " + i + " form: " + mailReceiver.getFromAddress()); System.out.println("Message " + i + " to: "+ mailReceiver.getMailAddress("to")); System.out.println("Message " + i + " cc: "+ mailReceiver.getMailAddress("cc")); System.out.println("Message " + i + " bcc: "+ mailReceiver.getMailAddress("bcc")); mailReceiver.setDateFormat("yy年MM月dd日 HH:mm"); System.out.println("Message " + i + " sentdate: "+ mailReceiver.getSentDate()); System.out.println("Message " + i + " Message-ID: "+ mailReceiver.getMessageId()); // 获得邮件内容 mailReceiver.getMailContent((Part) message[i]); System.out.println("Message " + i + " bodycontent: \r\n" + mailReceiver.getContent()); mailReceiver.setAttachPath("c:\\"); mailReceiver.saveAttachMent((Part) message[i]); } }
/** * Create a new {@link Transport} using the {@link Session} returned by {@link JavaMailSenderImpl#getSession() getSession()}. * * @param key A {@link URLName} containing the connection details * @return A new {@link Transport} */ @Override public Object makeObject(Object key) throws Exception { if ((key instanceof URLName) == false) { throw new IllegalArgumentException("Invlid key type"); } log.debug("Creating new Transport"); URLName urlName = (URLName) key; Transport transport = getSession().getTransport(urlName.getProtocol()); transport.connect(urlName.getHost(), urlName.getPort(), urlName.getUsername(), urlName.getPassword()); return transport; }
/** * Method to build Integration Flow for Mail. Suppress Warnings for * MailInboundChannelAdapterSpec. * @return Integration Flow object for Mail Source */ @SuppressWarnings({ "rawtypes", "unchecked" }) private IntegrationFlowBuilder getFlowBuilder() { IntegrationFlowBuilder flowBuilder; URLName urlName = this.properties.getUrl(); if (this.properties.isIdleImap()) { flowBuilder = getIdleImapFlow(urlName); } else { MailInboundChannelAdapterSpec adapterSpec; switch (urlName.getProtocol().toUpperCase()) { case "IMAP": case "IMAPS": adapterSpec = getImapFlowBuilder(urlName); break; case "POP3": case "POP3S": adapterSpec = getPop3FlowBuilder(urlName); break; default: throw new IllegalArgumentException( "Unsupported mail protocol: " + urlName.getProtocol()); } flowBuilder = IntegrationFlows.from( adapterSpec.javaMailProperties(getJavaMailProperties(urlName)) .userFlag(this.properties.getUserFlag()) .selectorExpression(this.properties.getExpression()) .shouldDeleteMessages(this.properties.isDelete())); } return flowBuilder; }
/** * Method to build Integration flow for IMAP Idle configuration. * @param urlName Mail source URL. * @return Integration Flow object IMAP IDLE. */ private IntegrationFlowBuilder getIdleImapFlow(URLName urlName) { return IntegrationFlows.from(Mail.imapIdleAdapter(urlName.toString()) .shouldDeleteMessages(this.properties.isDelete()) .userFlag(this.properties.getUserFlag()) .javaMailProperties(getJavaMailProperties(urlName)) .selectorExpression(this.properties.getExpression()) .shouldMarkMessagesAsRead(this.properties.isMarkAsRead())); }
private Properties getJavaMailProperties(URLName urlName) { Properties javaMailProperties = new Properties(); switch (urlName.getProtocol().toUpperCase()) { case "IMAP": javaMailProperties.setProperty("mail.imap.socketFactory.class", "javax.net.SocketFactory"); javaMailProperties.setProperty("mail.imap.socketFactory.fallback", "false"); javaMailProperties.setProperty("mail.store.protocol", "imap"); break; case "IMAPS": javaMailProperties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); javaMailProperties.setProperty("mail.imap.socketFactory.fallback", "false"); javaMailProperties.setProperty("mail.store.protocol", "imaps"); break; case "POP3": javaMailProperties.setProperty("mail.pop3.socketFactory.class", "javax.net.SocketFactory"); javaMailProperties.setProperty("mail.pop3.socketFactory.fallback", "false"); javaMailProperties.setProperty("mail.store.protocol", "pop3"); break; case "POP3S": javaMailProperties.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); javaMailProperties.setProperty("mail.pop3.socketFactory.fallback", "false"); javaMailProperties.setProperty("mail.store.protocol", "pop3s"); break; } javaMailProperties.putAll(this.properties.getJavaMailProperties()); return javaMailProperties; }
/** * Method to build Integration flow for IMAP Idle configuration. * @param urlName Mail source URL. * @return Integration Flow object IMAP IDLE. */ private IntegrationFlowBuilder getIdleImapFlow(URLName urlName) { return IntegrationFlows.from(Mail.imapIdleAdapter(urlName.toString()) .shouldDeleteMessages(this.properties.isDelete()) .javaMailProperties(getJavaMailProperties(urlName)) .selectorExpression(this.properties.getExpression()) .shouldMarkMessagesAsRead(this.properties.isMarkAsRead())); }
public static TransportStrategy newUrlNameStrategy(final URLName urlName) { return new TransportStrategy() { @Override public Transport getTransport(Session session) throws NoSuchProviderException { return session.getTransport(urlName); } }; }
@Override public URLName getURLName() throws RuntimeMessagingException { try { return delegate.getURLName(); } catch (MessagingException e) { throw new RuntimeMessagingException(e); } }
/** * connects to pop server * @throws MessagingException */ public void connect() throws MessagingException { Properties properties = new Properties(); String type=getTypeAsString(); properties.put("mail."+type+".host", server); properties.put("mail."+type+".port", new Double(port)); properties.put("mail."+type+".connectiontimeout", String.valueOf(timeout)); properties.put("mail."+type+".timeout", String.valueOf(timeout)); //properties.put("mail.mime.charset", "UTF-8"); if(TYPE_IMAP==getType()) properties.put("mail.imap.partialfetch", "false" ); else { if(secure) properties.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // will failover } _fldtry = username != null ? Session.getInstance(properties, new _Authenticator(username, password)) : Session.getInstance(properties); if(TYPE_POP3==getType() && secure) { URLName url = new URLName("pop3", server, port, "",username, password); _fldelse = new POP3SSLStore(_fldtry, url); } else { _fldelse = _fldtry.getStore(type); } if(!StringUtil.isEmpty(username))_fldelse.connect(server,username,password); else _fldelse.connect(); }
protected URLName updateUrlName(URLName urlName, Properties props) { String protocol = urlName.getProtocol(); String userName = urlName.getUsername(); String password = urlName.getPassword(); String host = urlName.getHost(); String file = urlName.getFile(); int port = urlName.getPort(); // check the username if (UtilValidate.isEmpty(userName)) { userName = props.getProperty("mail." + protocol + ".user"); if (UtilValidate.isEmpty(userName)) { userName = props.getProperty("mail.user"); } } // check the password; update with the non-standard property if (UtilValidate.isEmpty(password)) { password = props.getProperty("mail." + protocol + ".pass"); if (UtilValidate.isEmpty(password)) { password = props.getProperty("mail.pass"); } } // check the host if (UtilValidate.isEmpty(host)) { host = props.getProperty("mail." + protocol + ".host"); if (UtilValidate.isEmpty(host)) { host = props.getProperty("mail.host"); } } if (Debug.verboseOn()) Debug.logVerbose("Update URL - " + protocol + "://" + userName + "@" + host + ":" + port + "!" + password + ";" + file, module); return new URLName(protocol, host, port, file, userName, password); }
AbstractFileTransport(Session session, URLName urlname) { super(session, urlname); String s = session.getProperties().getProperty("mail.files.path", "."); directory = new File(s); if (! directory.exists() && ! directory.mkdirs()) { throw new IllegalArgumentException("Unable to create output directory " + directory.getAbsolutePath()); } }