javax.mail.URLName Java Examples

The following examples show how to use javax.mail.URLName. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SmtpJmsTransportTest.java    From javamail with Apache License 2.0 7 votes vote down vote up
@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());
}
 
Example #2
Source File: GreenMailServer.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: ThunderbirdMailbox.java    From mail-importer with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #4
Source File: MxPopTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
private void retrieveMail() throws NoSuchProviderException,
        MessagingException, IOException {
    Properties properties = new Properties();
    Session session = Session.getInstance(properties);
    Store store =
            session.getStore(new URLName("pop3://john:secret@localhost:"
                    + 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();
}
 
Example #5
Source File: AbstractFileTransportTest.java    From javamail with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #6
Source File: AbstractTransportTest.java    From javamail with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: Pop3SecureConnector.java    From bobcat with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #8
Source File: GreenMailServer.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #9
Source File: SmtpJmsTransportTest.java    From javamail with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #10
Source File: SmtpJmsTransportTest.java    From javamail with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #11
Source File: JavaxMailFolder.java    From mail-importer with Apache License 2.0 5 votes vote down vote up
@Override
public URLName getURLName() throws RuntimeMessagingException {
  try {
    return delegate.getURLName();
  } catch (MessagingException e) {
    throw new RuntimeMessagingException(e);
  }
}
 
Example #12
Source File: TransportStrategyFactory.java    From smtp-connection-pool with Apache License 2.0 5 votes vote down vote up
public static TransportStrategy newUrlNameStrategy(final URLName urlName) {
  return new TransportStrategy() {
    @Override
    public Transport getTransport(Session session) throws NoSuchProviderException {
      return session.getTransport(urlName);
    }
  };
}
 
Example #13
Source File: AbstractFileTransport.java    From javamail with Apache License 2.0 5 votes vote down vote up
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());
	}
}
 
Example #14
Source File: MailSourceConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #15
Source File: MailSourceConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
/**
 * 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()));
}
 
Example #16
Source File: EmailService.java    From Openfire with Apache License 2.0 5 votes vote down vote up
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 */ }
        }
    }
}
 
Example #17
Source File: AlfrescoJavaMailSender.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #18
Source File: PopMailImporter.java    From mireka with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #19
Source File: TransportMock.java    From iaf with Apache License 2.0 4 votes vote down vote up
public TransportMock(Session session, URLName urlname) {
	super(session, urlname);
	this.session = session;
}
 
Example #20
Source File: SmtpJmsTransportTest.java    From javamail with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testMissingTransportForDstProtocol() throws Exception {
    Properties properties = new Properties();
    properties.setProperty("mail.smtpjms.dstProtocol", "notExistingOne");
    new SmtpJmsTransport(Session.getInstance(properties), new URLName("jms"));
}
 
Example #21
Source File: IMAPMockStore.java    From javamail-mock2 with Apache License 2.0 4 votes vote down vote up
public IMAPMockStore(final Session session, final URLName url, final String name, final boolean isSSL) {
    super(session, url, name, isSSL);

    logger.debug("Created " + objectId);
}
 
Example #22
Source File: IMAPMockStore.java    From javamail-mock2 with Apache License 2.0 4 votes vote down vote up
@Override
public Folder getFolder(final URLName url) throws MessagingException {
    checkConnected();
    return getFolder(url.getFile());
}
 
Example #23
Source File: AbstractTransport.java    From javamail with Apache License 2.0 4 votes vote down vote up
AbstractTransport(Session session, URLName urlname) {
	super(session, urlname);
}
 
Example #24
Source File: POP3MockStore.java    From javamail-mock2 with Apache License 2.0 4 votes vote down vote up
public POP3MockStore(final Session session, final URLName url, final String name, final boolean isSSL) {
    super(session, url, name, isSSL);

    logger.debug("Created " + objectId);
}
 
Example #25
Source File: POP3MockStore.java    From javamail-mock2 with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized Folder getFolder(final URLName url) throws MessagingException {
    checkConnected();
    return getFolder(url.getFile());
}
 
Example #26
Source File: FileMsgTransport.java    From javamail with Apache License 2.0 4 votes vote down vote up
public FileMsgTransport(Session session, URLName urlname) {
	super(session, urlname);
}
 
Example #27
Source File: SMTPCommandTest.java    From greenmail with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    hostAddress = greenMail.getSmtp().getBindTo();
    port = greenMail.getSmtp().getPort();
    smtpURL = new URLName(hostAddress);
}
 
Example #28
Source File: NopTransport.java    From javamail with Apache License 2.0 4 votes vote down vote up
public NopTransport(Session session, URLName urlname) {
    super(session, urlname);
}
 
Example #29
Source File: BigAttachmentTest.java    From subethasmtp with Apache License 2.0 4 votes vote down vote up
/** */
public void testAttachments() throws Exception
{
	if (BIGFILE_PATH.equals(TO_CHANGE))
	{
		log.error("BigAttachmentTest: To complete this test you must change the BIGFILE_PATH var to point out a file on your disk !");
	}
	assertNotSame("BigAttachmentTest: To complete this test you must change the BIGFILE_PATH var to point out a file on your disk !", TO_CHANGE, BIGFILE_PATH);
	Properties props = System.getProperties();
	props.setProperty("mail.smtp.host", "localhost");
	props.setProperty("mail.smtp.port", SMTP_PORT+"");
	Session session = Session.getInstance(props);

	MimeMessage baseMsg = new MimeMessage(session);
	MimeBodyPart bp1 = new MimeBodyPart();
	bp1.setHeader("Content-Type", "text/plain");
	bp1.setContent("Hello World!!!", "text/plain; charset=\"ISO-8859-1\"");

	// Attach the file
	MimeBodyPart bp2 = new MimeBodyPart();
	FileDataSource fileAttachment = new FileDataSource(BIGFILE_PATH);
	DataHandler dh = new DataHandler(fileAttachment);
	bp2.setDataHandler(dh);
	bp2.setFileName(fileAttachment.getName());

	Multipart multipart = new MimeMultipart();
	multipart.addBodyPart(bp1);
	multipart.addBodyPart(bp2);

	baseMsg.setFrom(new InternetAddress("Ted <[email protected]>"));
	baseMsg.setRecipient(Message.RecipientType.TO, new InternetAddress(
			"[email protected]"));
	baseMsg.setSubject("Test Big attached file message");
	baseMsg.setContent(multipart);
	baseMsg.saveChanges();

	log.debug("Send started");
	Transport t = new SMTPTransport(session, new URLName("smtp://localhost:"+SMTP_PORT));
	long started = System.currentTimeMillis();
	t.connect();
	t.sendMessage(baseMsg, new Address[] {new InternetAddress(
			"[email protected]")});
	t.close();
	started = System.currentTimeMillis() - started;
	log.info("Elapsed ms = "+started);

	WiserMessage msg = this.server.getMessages().get(0);

	assertEquals(1, this.server.getMessages().size());
	assertEquals("[email protected]", msg.getEnvelopeReceiver());

	File compareFile = File.createTempFile("attached", ".tmp");
	log.debug("Writing received attachment ...");

	FileOutputStream fos = new FileOutputStream(compareFile);
	((MimeMultipart) msg.getMimeMessage().getContent()).getBodyPart(1).getDataHandler().writeTo(fos);
	fos.close();
	log.debug("Checking integrity ...");
	assertTrue(this.checkIntegrity(new File(BIGFILE_PATH), compareFile));
	log.debug("Checking integrity DONE");
	compareFile.delete();
}
 
Example #30
Source File: JavaMailSenderTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private MockTransport(Session session, URLName urlName) {
	super(session, urlName);
}