下面列出了怎么用javax.mail.URLName的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
@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 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 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);
}
@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);
}
@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());
}
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);
}
};
}
@Override
public URLName getURLName() throws RuntimeMessagingException {
try {
return delegate.getURLName();
} catch (MessagingException e) {
throw new RuntimeMessagingException(e);
}
}
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());
}
}
@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());
}
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 */ }
}
}
}
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());
}
private MockTransport(Session session, URLName urlName) {
super(session, urlName);
}
/**
* 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);
}
public CustomTransport(Session smtpSession, URLName urlName) {
super(smtpSession, urlName);
}
public MockEmailTransport(Session smtpSession, URLName urlName) {
super(smtpSession, urlName);
}
public MockEmailTransport(Session smtpSession, URLName urlName) {
super(smtpSession, urlName);
}
private MockTransport(Session session, URLName urlName) {
super(session, urlName);
}
public MockEmailTransport(Session smtpSession, URLName urlName) {
super(smtpSession, urlName);
}
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;
}