类javax.mail.URLName源码实例Demo

下面列出了怎么用javax.mail.URLName的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: micro-integrator   文件: GreenMailServer.java
/**
 * 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;
}
 
源代码2 项目: bobcat   文件: Pop3SecureConnector.java
@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);
  }
}
 
源代码3 项目: product-ei   文件: GreenMailServer.java
/**
 * 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;
}
 
源代码4 项目: mail-importer   文件: ThunderbirdMailbox.java
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);
}
 
源代码5 项目: javamail   文件: AbstractFileTransportTest.java
@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();
}
 
源代码6 项目: javamail   文件: AbstractTransportTest.java
@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);
    message = new MimeMessage(session);
    message.setFrom("Test <[email protected]>");
    connectionListener = Mockito.mock(ConnectionListener.class);
    transportListener = Mockito.mock(TransportListener.class);
    transport = new AbstractTransport(session, new URLName("AbstractDev")) {
        @Override
        public void sendMessage(Message message, Address[] addresses) throws MessagingException {
            validateAndPrepare(message, addresses);
        }
    };
    transport.addConnectionListener(connectionListener);
    transport.addTransportListener(transportListener);
}
 
源代码7 项目: javamail   文件: SmtpJmsTransportTest.java
@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);
}
 
源代码8 项目: javamail   文件: SmtpJmsTransportTest.java
@Test
public void testDoNotCheckFormHeader() throws Exception {
    Properties properties = new Properties();
    properties.setProperty("mail.smtpjms.validateFrom", "false");
    SmtpJmsTransport transport = new SmtpJmsTransport(Session.getInstance(properties), new URLName("jms"));
    Message message = Mockito.mock(Message.class);
    TransportListener listener = Mockito.mock(TransportListener.class);
    Address[] to = new Address[]{ new InternetAddress("[email protected]") };
    transport.addTransportListener(listener);
    transport.sendMessage(message, to);
    waitForListeners();
    ArgumentCaptor<TransportEvent> transportEventArgumentCaptor = ArgumentCaptor.forClass(TransportEvent.class);
    verify(listener).messageDelivered(transportEventArgumentCaptor.capture());
    TransportEvent event = transportEventArgumentCaptor.getValue();
    assertEquals(message, event.getMessage());
    assertEquals(TransportEvent.MESSAGE_DELIVERED, event.getType());
    assertArrayEquals(to, event.getValidSentAddresses());
}
 
源代码9 项目: mireka   文件: MxPopTest.java
private void retrieveMail() throws NoSuchProviderException,
        MessagingException, IOException {
    Properties properties = new Properties();
    Session session = Session.getInstance(properties);
    Store store =
            session.getStore(new URLName("pop3://john:[email protected]:"
                    + PORT_POP + "/INBOX"));
    store.connect();
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    Message[] messages = folder.getMessages();
    assertEquals(1, messages.length);
    Message message = messages[0];
    assertEquals("Hello World!\r\n", message.getContent());
    message.setFlag(Flags.Flag.DELETED, true);
    folder.close(true);
    store.close();
}
 
/**
 * 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 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()));
}
 
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;
}
 
public static TransportStrategy newUrlNameStrategy(final URLName urlName) {
  return new TransportStrategy() {
    @Override
    public Transport getTransport(Session session) throws NoSuchProviderException {
      return session.getTransport(urlName);
    }
  };
}
 
源代码14 项目: mail-importer   文件: JavaxMailFolder.java
@Override
public URLName getURLName() throws RuntimeMessagingException {
  try {
    return delegate.getURLName();
  } catch (MessagingException e) {
    throw new RuntimeMessagingException(e);
  }
}
 
源代码15 项目: javamail   文件: AbstractFileTransport.java
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());
	}
}
 
源代码16 项目: javamail   文件: SmtpJmsTransportTest.java
@Test
public void testSendInvalidPriority() throws Exception {
    SmtpJmsTransport transport = new SmtpJmsTransport(Session.getDefaultInstance(new Properties()), new URLName("jsm"));
    Message message = Mockito.mock(Message.class);
    when(message.getHeader(eq(SmtpJmsTransport.X_SEND_PRIORITY))).thenReturn(new String[]{"invalid"});
    when(message.getFrom()).thenReturn(new Address[] { new InternetAddress("[email protected]") });
    transport.sendMessage(message, new Address[] { new InternetAddress("[email protected]") });
    verify(bytesMessage, never()).setJMSPriority(anyInt());
}
 
源代码17 项目: Openfire   文件: EmailService.java
public void sendMessages() throws MessagingException {
    Transport transport = null;
    try {
        URLName url = new URLName("smtp", host, port, "", username, password);
        if (session == null) {
            createSession();
        }
        transport = new com.sun.mail.smtp.SMTPTransport(session, url);
        transport.connect(host, port, username, password);
        for (MimeMessage message : messages) {
            // Attempt to send message, but catch exceptions caused by invalid
            // addresses so that other messages can continue to be sent.
            try {
                transport.sendMessage(message,
                    message.getRecipients(MimeMessage.RecipientType.TO));
            }
            catch (AddressException | SendFailedException ae) {
                Log.error(ae.getMessage(), ae);
            }
        }
    }
    finally {
        if (transport != null) {
            try {
                transport.close();
            }
            catch (MessagingException e) { /* ignore */ }
        }
    }
}
 
源代码18 项目: mireka   文件: PopMailImporter.java
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());
}
 
源代码19 项目: spring-analysis-note   文件: JavaMailSenderTests.java
private MockTransport(Session session, URLName urlName) {
	super(session, urlName);
}
 
源代码20 项目: hop   文件: MailConnection.java
/**
 * Construct a new Database MailConnection
 *
 * @param protocol      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( ILogChannel log, int protocol, String server, int port, String username,
                       String password, boolean usessl, boolean useproxy, String proxyusername ) throws HopException {

  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 HopException( BaseMessages.getString( PKG, "JobGetMailsFromPOP.Error.NewConnection", Const.NVL(
      this.server, "" ) ), e );
  }
}
 
private MockTransport(Session session, URLName urlName) {
	super(session, urlName);
}
 
源代码22 项目: document-management-software   文件: MailUtil.java
public CustomTransport(Session smtpSession, URLName urlName) {
	super(smtpSession, urlName);
}
 
源代码23 项目: activiti6-boot2   文件: MockEmailTransport.java
public MockEmailTransport(Session smtpSession, URLName urlName) {
  super(smtpSession, urlName);
}
 
源代码24 项目: activiti6-boot2   文件: MockEmailTransport.java
public MockEmailTransport(Session smtpSession, URLName urlName) {
  super(smtpSession, urlName);
}
 
private MockTransport(Session session, URLName urlName) {
	super(session, urlName);
}
 
源代码26 项目: flowable-engine   文件: MockEmailTransport.java
public MockEmailTransport(Session smtpSession, URLName urlName) {
    super(smtpSession, urlName);
}
 
源代码27 项目: flowable-engine   文件: MockEmailTransport.java
public MockEmailTransport(Session smtpSession, URLName urlName) {
    super(smtpSession, urlName);
}
 
/**
 * @return the url
 */
@NotNull
public URLName getUrl() {
	return this.url;
}
 
/**
 * @param url the url to set
 */
public void setUrl(URLName url) {
	this.url = url;
}
 
/**
 * 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))
						.selectorExpression(this.properties.getExpression())
						.shouldDeleteMessages(this.properties.isDelete()),
				new Consumer<SourcePollingChannelAdapterSpec>() {

					@Override
					public void accept(
							SourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) {
						sourcePollingChannelAdapterSpec.poller(MailSourceConfiguration.this.defaultPoller);
					}

				});

	}
	return flowBuilder;
}
 
 类所在包
 类方法
 同包方法