javax.mail.NoSuchProviderException源码实例Demo

类javax.mail.NoSuchProviderException源码实例Demo

下面列出了javax.mail.NoSuchProviderException 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: javamail   文件: JMS2JavaMail.java
@PostConstruct
public void init() {
	if (session == null) {
		throw new IllegalStateException("JavaMail session is null.");
	}
	javaMailSessionDelegate = new JavaMailSessionDelegate() {
		@Override
		public Transport findTransport(String protocolToUse) throws NoSuchProviderException {
			return session.getTransport(protocolToUse);
		}
		@Override
		public MimeMessage createMimeMessage(InputStream inputStream) throws MessagingException {
			return new MimeMessage(session, inputStream);
		}
	};
}
 
源代码2 项目: 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();
}
 
源代码3 项目: spring-analysis-note   文件: JavaMailSenderImpl.java
/**
 * Obtain a Transport object from the given JavaMail Session,
 * using the configured protocol.
 * <p>Can be overridden in subclasses, e.g. to return a mock Transport object.
 * @see javax.mail.Session#getTransport(String)
 * @see #getSession()
 * @see #getProtocol()
 */
protected Transport getTransport(Session session) throws NoSuchProviderException {
	String protocol	= getProtocol();
	if (protocol == null) {
		protocol = session.getProperty("mail.transport.protocol");
		if (protocol == null) {
			protocol = DEFAULT_PROTOCOL;
		}
	}
	return session.getTransport(protocol);
}
 
@Test
public void javaMailSenderWithCustomSession() throws MessagingException {
	final Session session = Session.getInstance(new Properties());
	MockJavaMailSender sender = new MockJavaMailSender() {
		@Override
		protected Transport getTransport(Session sess) throws NoSuchProviderException {
			assertEquals(session, sess);
			return super.getTransport(sess);
		}
	};
	sender.setSession(session);
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage = sender.createMimeMessage();
	mimeMessage.setSubject("custom");
	mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	mimeMessage.setSentDate(new GregorianCalendar(2005, 3, 1).getTime());
	sender.send(mimeMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());
	assertEquals(1, sender.transport.getSentMessages().size());
	assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
 
@Test
public void javaMailProperties() throws MessagingException {
	Properties props = new Properties();
	props.setProperty("bogusKey", "bogusValue");
	MockJavaMailSender sender = new MockJavaMailSender() {
		@Override
		protected Transport getTransport(Session sess) throws NoSuchProviderException {
			assertEquals("bogusValue", sess.getProperty("bogusKey"));
			return super.getTransport(sess);
		}
	};
	sender.setJavaMailProperties(props);
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage = sender.createMimeMessage();
	mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	sender.send(mimeMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());
	assertEquals(1, sender.transport.getSentMessages().size());
	assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
 
/**
 * Obtain a Transport object from the given JavaMail Session,
 * using the configured protocol.
 * <p>Can be overridden in subclasses, e.g. to return a mock Transport object.
 * @see javax.mail.Session#getTransport(String)
 * @see #getSession()
 * @see #getProtocol()
 */
protected Transport getTransport(Session session) throws NoSuchProviderException {
	String protocol	= getProtocol();
	if (protocol == null) {
		protocol = session.getProperty("mail.transport.protocol");
		if (protocol == null) {
			protocol = DEFAULT_PROTOCOL;
		}
	}
	return session.getTransport(protocol);
}
 
@Test
public void javaMailSenderWithCustomSession() throws MessagingException {
	final Session session = Session.getInstance(new Properties());
	MockJavaMailSender sender = new MockJavaMailSender() {
		@Override
		protected Transport getTransport(Session sess) throws NoSuchProviderException {
			assertEquals(session, sess);
			return super.getTransport(sess);
		}
	};
	sender.setSession(session);
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage = sender.createMimeMessage();
	mimeMessage.setSubject("custom");
	mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	mimeMessage.setSentDate(new GregorianCalendar(2005, 3, 1).getTime());
	sender.send(mimeMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());
	assertEquals(1, sender.transport.getSentMessages().size());
	assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
 
@Test
public void javaMailProperties() throws MessagingException {
	Properties props = new Properties();
	props.setProperty("bogusKey", "bogusValue");
	MockJavaMailSender sender = new MockJavaMailSender() {
		@Override
		protected Transport getTransport(Session sess) throws NoSuchProviderException {
			assertEquals("bogusValue", sess.getProperty("bogusKey"));
			return super.getTransport(sess);
		}
	};
	sender.setJavaMailProperties(props);
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage = sender.createMimeMessage();
	mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	sender.send(mimeMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());
	assertEquals(1, sender.transport.getSentMessages().size());
	assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
 
/**
 * @return A new {@code PooledTransportWrapper} which borrows a pooled {@link Transport} on connect, and returns it to
 *             the pool on close.  
 */
@Override
protected Transport getTransport(Session session) throws NoSuchProviderException
{
    return new PooledTransportWrapper(transportPool, session, getProtocol());

}
 
源代码10 项目: ats-framework   文件: MailSender.java
/**
 * Initialize the SMTP session
 *
 * @throws ActionException
 */
private void initSession() throws ActionException {

    // initialize the mail session with the current properties
    session = Session.getInstance(mailProperties);
    // user can get more debug info with the session's debug mode
    session.setDebug(configurator.getMailSessionDebugMode());

    // initialize the SMPT transport
    try {
        transport = session.getTransport("smtp");
    } catch (NoSuchProviderException e) {
        throw new ActionException(e);
    }
}
 
源代码11 项目: lams   文件: JavaMailSenderImpl.java
/**
 * Obtain a Transport object from the given JavaMail Session,
 * using the configured protocol.
 * <p>Can be overridden in subclasses, e.g. to return a mock Transport object.
 * @see javax.mail.Session#getTransport(String)
 * @see #getSession()
 * @see #getProtocol()
 */
protected Transport getTransport(Session session) throws NoSuchProviderException {
	String protocol	= getProtocol();
	if (protocol == null) {
		protocol = session.getProperty("mail.transport.protocol");
		if (protocol == null) {
			protocol = DEFAULT_PROTOCOL;
		}
	}
	return session.getTransport(protocol);
}
 
源代码12 项目: Knowage-Server   文件: MailSessionBuilder.java
public Transport getTransport() throws NoSuchProviderException {
	if (securityMode == SecurityMode.SSL) {
		return session.getTransport("smtps");
	} else {
		return session.getTransport("smtp");
	}
}
 
源代码13 项目: spring4-understanding   文件: JavaMailSenderImpl.java
/**
 * Obtain a Transport object from the given JavaMail Session,
 * using the configured protocol.
 * <p>Can be overridden in subclasses, e.g. to return a mock Transport object.
 * @see javax.mail.Session#getTransport(String)
 * @see #getSession()
 * @see #getProtocol()
 */
protected Transport getTransport(Session session) throws NoSuchProviderException {
	String protocol	= getProtocol();
	if (protocol == null) {
		protocol = session.getProperty("mail.transport.protocol");
		if (protocol == null) {
			protocol = DEFAULT_PROTOCOL;
		}
	}
	return session.getTransport(protocol);
}
 
@Test
public void javaMailSenderWithCustomSession() throws MessagingException {
	final Session session = Session.getInstance(new Properties());
	MockJavaMailSender sender = new MockJavaMailSender() {
		@Override
		protected Transport getTransport(Session sess) throws NoSuchProviderException {
			assertEquals(session, sess);
			return super.getTransport(sess);
		}
	};
	sender.setSession(session);
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage = sender.createMimeMessage();
	mimeMessage.setSubject("custom");
	mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	mimeMessage.setSentDate(new GregorianCalendar(2005, 3, 1).getTime());
	sender.send(mimeMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());
	assertEquals(1, sender.transport.getSentMessages().size());
	assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
 
@Test
public void javaMailProperties() throws MessagingException {
	Properties props = new Properties();
	props.setProperty("bogusKey", "bogusValue");
	MockJavaMailSender sender = new MockJavaMailSender() {
		@Override
		protected Transport getTransport(Session sess) throws NoSuchProviderException {
			assertEquals("bogusValue", sess.getProperty("bogusKey"));
			return super.getTransport(sess);
		}
	};
	sender.setJavaMailProperties(props);
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage = sender.createMimeMessage();
	mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	sender.send(mimeMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());
	assertEquals(1, sender.transport.getSentMessages().size());
	assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
 
public static TransportStrategy newSessiontStrategy() {
  return new TransportStrategy() {
    @Override
    public Transport getTransport(Session session) throws NoSuchProviderException {
      return session.getTransport();
    }
  };
}
 
public static TransportStrategy newProtocolStrategy(final String protocol) {
  return new TransportStrategy() {
    @Override
    public Transport getTransport(Session session) throws NoSuchProviderException {
      return session.getTransport(protocol);
    }
  };
}
 
public static TransportStrategy newUrlNameStrategy(final URLName urlName) {
  return new TransportStrategy() {
    @Override
    public Transport getTransport(Session session) throws NoSuchProviderException {
      return session.getTransport(urlName);
    }
  };
}
 
public static TransportStrategy newAddressStrategy(final Address address) {
  return new TransportStrategy() {
    @Override
    public Transport getTransport(Session session) throws NoSuchProviderException {
      return session.getTransport(address);
    }
  };
}
 
public static TransportStrategy newProviderStrategy(final Provider provider) {
  return new TransportStrategy() {
    @Override
    public Transport getTransport(Session session) throws NoSuchProviderException {
      return session.getTransport(provider);
    }
  };
}
 
源代码21 项目: packagedrone   文件: DefaultMailService.java
private void sendMessage ( final Message message ) throws MessagingException, NoSuchProviderException
{
    final ClassLoader oldClassLoader = Thread.currentThread ().getContextClassLoader ();
    Thread.currentThread ().setContextClassLoader ( getClass ().getClassLoader () );

    try
    {

        // commit

        message.saveChanges ();

        // connect

        final Transport transport = this.session.getTransport ();
        transport.connect ();

        // send

        try
        {
            transport.sendMessage ( message, message.getAllRecipients () );
        }
        finally
        {
            // close

            transport.close ();
        }
    }
    finally
    {
        Thread.currentThread ().setContextClassLoader ( oldClassLoader );
    }
}
 
源代码22 项目: baleen   文件: EmailReader.java
@Override
protected void doInitialize(UimaContext context) throws ResourceInitializationException {
  validateParams();

  Authenticator authenticator =
      new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(user, pass);
        }
      };

  Properties prop = new Properties();
  prop.put("mail.store.protocol", protocol);
  prop.put("mail.host", server);
  prop.put("mail." + protocol + ".port", port);
  prop.put("mail.user", user);

  Session session = Session.getInstance(prop, authenticator);
  try {
    store = session.getStore();
  } catch (NoSuchProviderException e) {
    throw new ResourceInitializationException(e);
  }

  try {
    store.connect();
    inboxFolder = store.getFolder(inbox);
    reopenConnection();
  } catch (MessagingException me) {
    throw new ResourceInitializationException(me);
  }
}
 
源代码23 项目: FlexibleLogin   文件: SendMailTask.java
@Override
public void run() {
    ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
    try (Transport transport = session.getTransport()) {
        // Prevent UnsupportedDataTypeException: no object DCH for MIME type multipart/alternative
        // cf. https://stackoverflow.com/questions/21856211/unsupporteddatatypeexception-no-object-dch-for-mime-type
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
        mc.addMailcap("text/html;; x-java-content-handler=flexiblelogin.mail.handlers.text_html");
        mc.addMailcap("text/xml;; x-java-content-handler=flexiblelogin.mail.handlers.text_xml");
        mc.addMailcap("text/plain;; x-java-content-handler=flexiblelogin.mail.handlers.text_plain");
        mc.addMailcap("multipart/*;; x-java-content-handler=flexiblelogin.mail.handlers.multipart_mixed");
        mc.addMailcap("message/rfc822;; x-java-content- handler=flexiblelogin.mail.handlers.message_rfc822");

        MailConfig mailConfig = plugin.getConfigManager().getGeneral().getMail();

        //connect to host and send message
        if (!transport.isConnected()) {
            String password = mailConfig.getPassword();
            transport.connect(mailConfig.getHost(), mailConfig.getAccount(), password);
        }

        transport.sendMessage(mail, mail.getAllRecipients());
        player.sendMessage(plugin.getConfigManager().getText().getMailSent());
    } catch (NoSuchProviderException providerEx) {
        plugin.getLogger().error("Transport provider not found", providerEx);
        plugin.getLogger().error("Registered providers: {}", Arrays.asList(session.getProviders()));

        player.sendMessage(plugin.getConfigManager().getText().getErrorExecutingCommand());
    } catch (MessagingException messagingEx) {
        plugin.getLogger().error("Error sending mail", messagingEx);
        player.sendMessage(plugin.getConfigManager().getText().getErrorExecutingCommand());
    } finally {
        Thread.currentThread().setContextClassLoader(oldClassLoader);
    }
}
 
源代码24 项目: FlexibleLogin   文件: ForgotPasswordCommand.java
private Session buildSession(MailConfig emailConfig) {
    Properties properties = new Properties();
    properties.setProperty("mail.smtp.host", emailConfig.getHost());
    properties.setProperty("mail.smtp.auth", "true");
    properties.setProperty("mail.smtp.port", String.valueOf(emailConfig.getPort()));

    //ssl
    properties.setProperty("mail.smtp.socketFactory.port", String.valueOf(emailConfig.getPort()));
    properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.setProperty("mail.smtp.socketFactory.fallback", "false");
    properties.setProperty("mail.smtp.starttls.enable", String.valueOf(true));
    properties.setProperty("mail.smtp.ssl.checkserveridentity", "true");

    //we only need to send the message so we use smtps
    properties.setProperty("mail.transport.protocol", "smtps");

    //explicit override stmp provider because of issues with relocation
    Session session = Session.getDefaultInstance(properties);
    try {
        session.setProvider(new Provider(Type.TRANSPORT, "smtps",
                "flexiblelogin.mail.smtp.SMTPSSLTransport", "Oracle", "1.6.0"));
    } catch (NoSuchProviderException noSuchProvider) {
        logger.error("Failed to add SMTP provider", noSuchProvider);
    }

    return session;
}
 
源代码25 项目: javamail   文件: JMS2JavaMailTest.java
@Test
public void testFailNoTransportForProtocol() throws Exception {
    BytesMessage message = bytesMessageFor(source, new Address[]{new InternetAddress("[email protected]")});
    Exception exception = new NoSuchProviderException();
    when(sessionDelegate.findTransport(eq("testProto"))).thenThrow(exception);
    jms2JavaMail.onMessage(message);
    verify(message, never()).acknowledge();
    ArgumentCaptor<Exception> exceptionArgumentCaptor = ArgumentCaptor.forClass(Exception.class);
    verify(javaMailJMSStatistics, never()).onSuccess(any(MimeMessage.class), any(Address[].class));
    verify(javaMailJMSStatistics, times(1)).onFailure(any(MimeMessage.class), any(Address[].class), exceptionArgumentCaptor.capture());
    Assert.assertEquals(exception, exceptionArgumentCaptor.getValue());
}
 
源代码26 项目: cs-actions   文件: SSLUtils.java
public static Store configureStoreWithSSL(Properties props, Authenticator auth, MailInput input) throws NoSuchProviderException {
    configureWithSSL(props, input);
    URLName url = new URLName(input.getProtocol(), input.getHostname(), input.getPort(), StringUtils.EMPTY,
            input.getUsername(), input.getPassword());
    Session session = Session.getInstance(props, auth);
    return session.getStore(url);
}
 
源代码27 项目: spring-analysis-note   文件: JavaMailSenderTests.java
@Override
protected Transport getTransport(Session session) throws NoSuchProviderException {
	this.transport = new MockTransport(session, null);
	return transport;
}
 
@Override
protected Transport getTransport(Session session) throws NoSuchProviderException {
	this.transport = new MockTransport(session, null);
	return transport;
}
 
源代码29 项目: FairEmail   文件: EmailService.java
EmailService(Context context, String protocol, String realm, boolean insecure, boolean debug) throws NoSuchProviderException {
    this(context, protocol, realm, insecure, PURPOSE_USE, debug);
}
 
源代码30 项目: FairEmail   文件: EmailService.java
EmailService(Context context, String protocol, String realm, boolean insecure, int purpose, boolean debug) throws NoSuchProviderException {
    this.context = context.getApplicationContext();
    this.protocol = protocol;
    this.insecure = insecure;
    this.purpose = purpose;
    this.debug = debug;

    properties = MessageHelper.getSessionProperties();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    this.harden = prefs.getBoolean("ssl_harden", false);

    boolean auth_sasl = prefs.getBoolean("auth_sasl", true);

    properties.put("mail.event.scope", "folder");
    properties.put("mail.event.executor", executor);

    properties.put("mail." + protocol + ".sasl.enable", "true");
    if (auth_sasl) {
        properties.put("mail." + protocol + ".sasl.mechanisms", "CRAM-MD5");
        properties.put("mail." + protocol + ".sasl.realm", realm == null ? "" : realm);
    }
    properties.put("mail." + protocol + ".auth.ntlm.domain", realm == null ? "" : realm);

    // writetimeout: one thread overhead
    int timeout = prefs.getInt("timeout", DEFAULT_CONNECT_TIMEOUT) * 1000;
    Log.i("Timeout=" + timeout);
    if (purpose == PURPOSE_SEARCH) {
        properties.put("mail." + protocol + ".connectiontimeout", Integer.toString(timeout));
        properties.put("mail." + protocol + ".writetimeout", Integer.toString(SEARCH_TIMEOUT));
        properties.put("mail." + protocol + ".timeout", Integer.toString(SEARCH_TIMEOUT));
    } else {
        properties.put("mail." + protocol + ".connectiontimeout", Integer.toString(timeout));
        properties.put("mail." + protocol + ".writetimeout", Integer.toString(timeout * 2));
        properties.put("mail." + protocol + ".timeout", Integer.toString(timeout * 2));
    }

    if (debug && BuildConfig.DEBUG)
        properties.put("mail.debug.auth", "true");

    if ("pop3".equals(protocol) || "pop3s".equals(protocol)) {
        // https://javaee.github.io/javamail/docs/api/com/sun/mail/pop3/package-summary.html#properties
        properties.put("mail.pop3s.starttls.enable", "false");

        properties.put("mail.pop3.starttls.enable", "true");
        properties.put("mail.pop3.starttls.required", Boolean.toString(!insecure));

    } else if ("imap".equals(protocol) || "imaps".equals(protocol) || "gimaps".equals(protocol)) {
        // https://javaee.github.io/javamail/docs/api/com/sun/mail/imap/package-summary.html#properties
        properties.put("mail.imaps.starttls.enable", "false");

        properties.put("mail.imap.starttls.enable", "true");
        properties.put("mail.imap.starttls.required", Boolean.toString(!insecure));

        properties.put("mail." + protocol + ".separatestoreconnection", "true");
        properties.put("mail." + protocol + ".connectionpool.debug", "true");
        properties.put("mail." + protocol + ".connectionpoolsize", "1");
        properties.put("mail." + protocol + ".connectionpooltimeout", Integer.toString(POOL_TIMEOUT));

        properties.put("mail." + protocol + ".finalizecleanclose", "false");
        //properties.put("mail." + protocol + ".closefoldersonstorefailure", "false");

        // https://tools.ietf.org/html/rfc4978
        // https://docs.oracle.com/javase/8/docs/api/java/util/zip/Deflater.html
        properties.put("mail." + protocol + ".compress.enable", "true");
        //properties.put("mail.imaps.compress.level", "-1");
        //properties.put("mail.imaps.compress.strategy", "0");

        properties.put("mail." + protocol + ".throwsearchexception", "true");
        properties.put("mail." + protocol + ".fetchsize", Integer.toString(FETCH_SIZE));
        properties.put("mail." + protocol + ".peek", "true");
        properties.put("mail." + protocol + ".appendbuffersize", Integer.toString(APPEND_BUFFER_SIZE));

    } else if ("smtp".equals(protocol) || "smtps".equals(protocol)) {
        // https://javaee.github.io/javamail/docs/api/com/sun/mail/smtp/package-summary.html#properties
        properties.put("mail.smtps.starttls.enable", "false");

        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.starttls.required", Boolean.toString(!insecure));

        properties.put("mail." + protocol + ".auth", "true");

    } else
        throw new NoSuchProviderException(protocol);
}
 
源代码评论
动弹
沙发等你来抢
 类所在包
 类方法
 同包方法