org.subethamail.smtp.server.SMTPServer Java Examples

The following examples show how to use org.subethamail.smtp.server.SMTPServer. 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: SakaiMessageHandlerFactory.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public void init() {
    Objects.requireNonNull(rb, "ResourceLoader must be set");
    Objects.requireNonNull(serverConfigurationService, "ServerConfigurationService must be set");
    Objects.requireNonNull(entityManager, "EntityManager must be set");
    Objects.requireNonNull(aliasService, "AliasService must be set");
    Objects.requireNonNull(userDirectoryService, "UserDirectoryService must be set");
    Objects.requireNonNull(siteService, "SiteService must be set");
    Objects.requireNonNull(threadLocalManager, "ThreadLocalManager must be set");
    Objects.requireNonNull(contentHostingService, "ContentHostingService must be set");
    Objects.requireNonNull(mailArchiveService, "MailArchiveService must be set");
    Objects.requireNonNull(sessionManager, "SessionManager must be set");

    if (serverConfigurationService.getBoolean("smtp.enabled", false)) {
        server = new SMTPServer(this);

        server.setHostName(serverConfigurationService.getServerName());
        server.setPort(serverConfigurationService.getInt("smtp.port", 25));
        server.setSoftwareName("SubEthaSMTP - Sakai (" + serverConfigurationService.getString("sakai.version", "unknown") +
                ")");
        // We don't support smtp.dns.1 and smtp.dns.2
        server.setMaxConnections(100);
        server.start();
    }
}
 
Example #2
Source File: SubethaEmailServer.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void startup()
{
    serverImpl = new SMTPServer(new HandlerFactory());
    
    // MER - May need to override SMTPServer.createSSLSocket to specify non default keystore.
    serverImpl.setPort(getPort());
    serverImpl.setHostName(getDomain());
    serverImpl.setMaxConnections(getMaxConnections());
    
    serverImpl.setHideTLS(isHideTLS());
    serverImpl.setEnableTLS(isEnableTLS());
    serverImpl.setRequireTLS(isRequireTLS());
    
    if(isAuthenticate())
    {
        AuthenticationHandlerFactory authenticationHandler = new EasyAuthenticationHandlerFactory(new AlfrescoLoginUsernamePasswordValidator());
        serverImpl.setAuthenticationHandlerFactory(authenticationHandler);
    }
    
    serverImpl.start();
    log.info("Inbound SMTP Email Server has started successfully, on hostName:" + getDomain() + "port:" + getPort());
}
 
Example #3
Source File: SakaiMessageHandlerFactory.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public void init() {
    Objects.requireNonNull(rb, "ResourceLoader must be set");
    Objects.requireNonNull(serverConfigurationService, "ServerConfigurationService must be set");
    Objects.requireNonNull(entityManager, "EntityManager must be set");
    Objects.requireNonNull(aliasService, "AliasService must be set");
    Objects.requireNonNull(userDirectoryService, "UserDirectoryService must be set");
    Objects.requireNonNull(siteService, "SiteService must be set");
    Objects.requireNonNull(threadLocalManager, "ThreadLocalManager must be set");
    Objects.requireNonNull(contentHostingService, "ContentHostingService must be set");
    Objects.requireNonNull(mailArchiveService, "MailArchiveService must be set");
    Objects.requireNonNull(sessionManager, "SessionManager must be set");

    if (serverConfigurationService.getBoolean("smtp.enabled", false)) {
        server = new SMTPServer(this);

        server.setHostName(serverConfigurationService.getServerName());
        server.setPort(serverConfigurationService.getInt("smtp.port", 25));
        server.setSoftwareName("SubEthaSMTP - Sakai (" + serverConfigurationService.getString("sakai.version", "unknown") +
                ")");
        // We don't support smtp.dns.1 and smtp.dns.2
        server.setMaxConnections(100);
        server.start();
    }
}
 
Example #4
Source File: SmtpServerConfiguratorTest.java    From fake-smtp-server with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConfigureAuthenticationWhenAuthenticationIsConfiguredProperly(){
    var username = "username";
    var password = "password";
    var authentication = mock(FakeSmtpConfigurationProperties.Authentication.class);
    when(authentication.getUsername()).thenReturn(username);
    when(authentication.getPassword()).thenReturn(password);
    when(fakeSmtpConfigurationProperties.getAuthentication()).thenReturn(authentication);

    var smtpServer = mock(SMTPServer.class);

    sut.configure(smtpServer);

    var argumentCaptor = ArgumentCaptor.forClass(AuthenticationHandlerFactory.class);
    verify(smtpServer).setAuthenticationHandlerFactory(argumentCaptor.capture());

    var authenticationHandlerFactory = argumentCaptor.getValue();
    assertNotNull(authenticationHandlerFactory);
    assertThat(authenticationHandlerFactory, instanceOf(EasyAuthenticationHandlerFactory.class));

    var easyAuthenticationHandlerFactory = (EasyAuthenticationHandlerFactory)authenticationHandlerFactory;
    assertSame(basicUsernamePasswordValidator, easyAuthenticationHandlerFactory.getValidator());
}
 
Example #5
Source File: ListenSMTP.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSessionFactory sessionFactory) throws ProcessException {
    if (smtp == null) {
        try {
            final SMTPServer server = prepareServer(context, sessionFactory);
            server.start();
            smtp = server;
        } catch (final Exception ex) {//have to catch exception due to awkward exception handling in subethasmtp
            smtp = null;
            getLogger().error("Unable to start SMTP server due to " + ex.getMessage(), ex);
        }
    }
    context.yield();//nothing really to do here since threading managed by smtp server sessions
}
 
Example #6
Source File: TestMailManager.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testSendMailWithChangedPort() throws Throwable {
	
	MockMessageHandlerFactory myFactory2 = new MockMessageHandlerFactory();
	MockAuthenticationHandlerFactory myAuthFactory2 = new MockAuthenticationHandlerFactory();
	SMTPServer smtpServer2 = new SMTPServer(myFactory2, myAuthFactory2);
       smtpServer2.setPort(25001);
       smtpServer2.start();
	
	MailConfig originaryConfig = this._mailManager.getMailConfig();
	try {
		MailConfig config = this._mailManager.getMailConfig();
		config.setSmtpPort(25001);
		this._mailManager.updateMailConfig(config);
		String[] mailAddresses = JpmailTestHelper.MAIL_ADDRESSES;
		this._mailManager.sendMail(MAIL_TEXT, "Mail semplice", mailAddresses, mailAddresses, mailAddresses, SENDER_CODE);
	} catch (Throwable t) {
		throw t;
	} finally {
		this._mailManager.updateMailConfig(originaryConfig);
		this.checkOriginaryConfig(originaryConfig);
	}
	
	myFactory2 = null;
	myAuthFactory2 = null;
	smtpServer2.stop();
	smtpServer2 = null;
}
 
Example #7
Source File: HelpCommand.java    From subethasmtp with Apache License 2.0 5 votes vote down vote up
/** */
protected String getFormattedTopicList(SMTPServer server)
{
	StringBuilder sb = new StringBuilder();
	for (String key : server.getCommandHandler().getVerbs())
    {
    	sb.append("214-     " + key + "\r\n");
    }
	return sb.toString();
}
 
Example #8
Source File: HelpCommand.java    From subethasmtp with Apache License 2.0 5 votes vote down vote up
/** */
private String getCommandMessage(SMTPServer server)
{
	return "214-"
			+ server.getSoftwareName()
			+ " on "
			+ server.getHostName()
			+ "\r\n"
			+ "214-Topics:\r\n"
			+ this.getFormattedTopicList(server)
			+ "214-For more info use \"HELP <topic>\".\r\n"
			+ "214 End of HELP info";
}
 
Example #9
Source File: TestMailManager.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
	this._myFactory = new MockMessageHandlerFactory();
	this._myAuthFactory = new MockAuthenticationHandlerFactory();
	this._smtpServer = new SMTPServer(this._myFactory, this._myAuthFactory);
	this._smtpServer.setPort(25000);
	this._smtpServer.start();
	super.setUp();
}
 
Example #10
Source File: ListenSMTP.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSessionFactory sessionFactory) throws ProcessException {
    if (smtp == null) {
        try {
            final SMTPServer server = prepareServer(context, sessionFactory);
            server.start();
            getLogger().debug("Started SMTP Server on port " + server.getPort());
            smtp = server;
        } catch (final Exception ex) {//have to catch exception due to awkward exception handling in subethasmtp
            smtp = null;
            getLogger().error("Unable to start SMTP server due to " + ex.getMessage(), ex);
        }
    }
    context.yield();//nothing really to do here since threading managed by smtp server sessions
}
 
Example #11
Source File: HoldMailSMTPServer.java    From holdmail with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void startup() {

    smtpServer = new SMTPServer(handlerFactory);
    smtpServer.setSoftwareName(HoldMailSMTPServer.class.getSimpleName() + " SMTP");
    smtpServer.setPort(smtpServerPort);
    smtpServer.start();

}
 
Example #12
Source File: SmtpServerImplTest.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateNewInstanceAndDelegateCallsToRealImplementation(){
    var delegate = mock(SMTPServer.class);

    var sut = new SmtpServerImpl(delegate);

    sut.start();
    verify(delegate).start();

    sut.stop();
    verify(delegate).stop();
}
 
Example #13
Source File: SmtpServerConfiguratorTest.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSkipConfigurationOfAuthenticationWhenPasswordIsEmptyString(){
    var username = "username";
    var authentication = mock(FakeSmtpConfigurationProperties.Authentication.class);
    when(authentication.getUsername()).thenReturn(username);
    when(authentication.getPassword()).thenReturn("");
    when(fakeSmtpConfigurationProperties.getAuthentication()).thenReturn(authentication);

    var smtpServer = mock(SMTPServer.class);

    sut.configure(smtpServer);

    verify(smtpServer, never()).setAuthenticationHandlerFactory(any(AuthenticationHandlerFactory.class));
    verify(logger).error(startsWith("Password"));
}
 
Example #14
Source File: SmtpServerConfiguratorTest.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSkipConfigurationOfAuthenticationWhenPasswordIsNull(){
    var username = "username";
    var authentication = mock(FakeSmtpConfigurationProperties.Authentication.class);
    when(authentication.getUsername()).thenReturn(username);
    when(authentication.getPassword()).thenReturn(null);
    when(fakeSmtpConfigurationProperties.getAuthentication()).thenReturn(authentication);

    var smtpServer = mock(SMTPServer.class);

    sut.configure(smtpServer);

    verify(smtpServer, never()).setAuthenticationHandlerFactory(any(AuthenticationHandlerFactory.class));
    verify(logger).error(startsWith("Password"));
}
 
Example #15
Source File: SmtpServerConfiguratorTest.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSkipConfigurationOfAuthenticationWhenUsernameIsEmptyString(){
    var authentication = mock(FakeSmtpConfigurationProperties.Authentication.class);
    when(authentication.getUsername()).thenReturn("");
    when(fakeSmtpConfigurationProperties.getAuthentication()).thenReturn(authentication);

    var smtpServer = mock(SMTPServer.class);

    sut.configure(smtpServer);

    verify(smtpServer, never()).setAuthenticationHandlerFactory(any(AuthenticationHandlerFactory.class));
    verify(logger).error(startsWith("Username"));
}
 
Example #16
Source File: SmtpServerConfiguratorTest.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSkipConfigurationOfAuthenticationWhenUsernameIsNull(){
    var authentication = mock(FakeSmtpConfigurationProperties.Authentication.class);
    when(authentication.getUsername()).thenReturn(null);
    when(fakeSmtpConfigurationProperties.getAuthentication()).thenReturn(authentication);

    var smtpServer = mock(SMTPServer.class);

    sut.configure(smtpServer);

    verify(smtpServer, never()).setAuthenticationHandlerFactory(any(AuthenticationHandlerFactory.class));
    verify(logger).error(startsWith("Username"));
}
 
Example #17
Source File: SmtpServerConfiguratorTest.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConfigureBasicParameters(){
    var port = 1234;
    var bindingAddress = mock(InetAddress.class);
    when(fakeSmtpConfigurationProperties.getPort()).thenReturn(port);
    when(fakeSmtpConfigurationProperties.getBindAddress()).thenReturn(bindingAddress);

    var smtpServer = mock(SMTPServer.class);

    sut.configure(smtpServer);

    verify(smtpServer).setPort(port);
    verify(smtpServer).setBindAddress(bindingAddress);
    verify(smtpServer, never()).setAuthenticationHandlerFactory(any(AuthenticationHandlerFactory.class));
}
 
Example #18
Source File: SmtpServerFactoryImpl.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
@Override
public SmtpServer create() {
    var simpleMessageListenerAdapter = new SimpleMessageListenerAdapter(messageListener);
    var smtpServer = new SMTPServer(simpleMessageListenerAdapter);
    configurator.configure(smtpServer);
    return new SmtpServerImpl(smtpServer);
}
 
Example #19
Source File: SmtpServerConfigurator.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
private void configureAuthentication(SMTPServer smtpServer, FakeSmtpConfigurationProperties.Authentication authentication) {
    if (StringUtils.isEmpty(authentication.getUsername())) {
        logger.error("Username is missing; skip configuration of authentication");
    } else if (StringUtils.isEmpty(authentication.getPassword())) {
        logger.error("Password is missing; skip configuration of authentication");
    } else {
        logger.info("Setup simple username and password authentication for SMTP server");
        smtpServer.setAuthenticationHandlerFactory(new EasyAuthenticationHandlerFactory(basicUsernamePasswordValidator));
    }
}
 
Example #20
Source File: SmtpServerConfigurator.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
public void configure(SMTPServer smtpServer) {
    smtpServer.setPort(fakeSmtpConfigurationProperties.getPort());
    smtpServer.setBindAddress(fakeSmtpConfigurationProperties.getBindAddress());
    if (fakeSmtpConfigurationProperties.getAuthentication() != null) {
        configureAuthentication(smtpServer, fakeSmtpConfigurationProperties.getAuthentication());
    }
}
 
Example #21
Source File: SslMailServer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void start() {
    smtpServer = new SMTPServer(messageHandlerFactory);
    smtpServer.setHostName(HOST);
    smtpServer.setPort(Integer.parseInt(PORT));
    smtpServer.start();

    log.info("Started mail server (" + smtpServer.getHostName() + ":" + smtpServer.getPort() + ")");
}
 
Example #22
Source File: AwsSmtpRelay.java    From aws-smtp-relay with GNU Lesser General Public License v3.0 5 votes vote down vote up
void run() throws UnknownHostException {

        String bindAddress = cmd.hasOption("b") ? cmd.getOptionValue("b") : "127.0.0.1";

        SMTPServer smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(this));
        smtpServer.setBindAddress(InetAddress.getByName(bindAddress));
        if (cmd.hasOption("p")) {
            smtpServer.setPort(Integer.parseInt(cmd.getOptionValue("p")));
        } else {
            smtpServer.setPort(10025);
        }
        smtpServer.start();
    }
 
Example #23
Source File: ListenSMTP.java    From nifi with Apache License 2.0 4 votes vote down vote up
private SMTPServer prepareServer(final ProcessContext context, final ProcessSessionFactory sessionFactory) {
    final int port = context.getProperty(SMTP_PORT).asInteger();
    final String host = context.getProperty(SMTP_HOSTNAME).getValue();
    final ComponentLog log = getLogger();
    final int maxMessageSize = context.getProperty(SMTP_MAXIMUM_MSG_SIZE).asDataSize(DataUnit.B).intValue();
    //create message handler factory
    final MessageHandlerFactory messageHandlerFactory = (final MessageContext mc) -> {
        return new SmtpConsumer(mc, sessionFactory, port, host, log, maxMessageSize);
    };
    //create smtp server
    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    final SMTPServer smtpServer = sslContextService == null ? new SMTPServer(messageHandlerFactory) : new SMTPServer(messageHandlerFactory) {
        @Override
        public SSLSocket createSSLSocket(Socket socket) throws IOException {
            InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
            String clientAuth = context.getProperty(CLIENT_AUTH).getValue();
            SSLContext sslContext = sslContextService.createSSLContext(SslContextFactory.ClientAuth.valueOf(clientAuth));
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            SSLSocket sslSocket = (SSLSocket) (socketFactory.createSocket(socket, remoteAddress.getHostName(), socket.getPort(), true));
            sslSocket.setUseClientMode(false);

            if (SslContextFactory.ClientAuth.REQUIRED.toString().equals(clientAuth)) {
                this.setRequireTLS(true);
                sslSocket.setNeedClientAuth(true);
            }
            return sslSocket;
        }
    };
    if (sslContextService != null) {
        smtpServer.setEnableTLS(true);
    } else {
        smtpServer.setHideTLS(true);
    }
    smtpServer.setSoftwareName("Apache NiFi SMTP");
    smtpServer.setPort(port);
    smtpServer.setMaxConnections(context.getProperty(SMTP_MAXIMUM_CONNECTIONS).asInteger());
    smtpServer.setMaxMessageSize(maxMessageSize);
    smtpServer.setConnectionTimeout(context.getProperty(SMTP_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    if (context.getProperty(SMTP_HOSTNAME).isSet()) {
        smtpServer.setHostName(context.getProperty(SMTP_HOSTNAME).getValue());
    }
    return smtpServer;
}
 
Example #24
Source File: ListenSMTP.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
private SMTPServer prepareServer(final ProcessContext context, final ProcessSessionFactory sessionFactory) {
    final int port = context.getProperty(SMTP_PORT).asInteger();
    final String host = context.getProperty(SMTP_HOSTNAME).getValue();
    final ComponentLog log = getLogger();
    final int maxMessageSize = context.getProperty(SMTP_MAXIMUM_MSG_SIZE).asDataSize(DataUnit.B).intValue();
    //create message handler factory
    final MessageHandlerFactory messageHandlerFactory = (final MessageContext mc) -> {
        return new SmtpConsumer(mc, sessionFactory, port, host, log, maxMessageSize);
    };
    //create smtp server
    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    final SMTPServer smtpServer = sslContextService == null ? new SMTPServer(messageHandlerFactory) : new SMTPServer(messageHandlerFactory) {
        @Override
        public SSLSocket createSSLSocket(Socket socket) throws IOException {
            InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
            String clientAuth = context.getProperty(CLIENT_AUTH).getValue();
            SSLContext sslContext = sslContextService.createSSLContext(SSLContextService.ClientAuth.valueOf(clientAuth));
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            SSLSocket sslSocket = (SSLSocket) (socketFactory.createSocket(socket, remoteAddress.getHostName(), socket.getPort(), true));
            sslSocket.setUseClientMode(false);

            if (SSLContextService.ClientAuth.REQUIRED.toString().equals(clientAuth)) {
                this.setRequireTLS(true);
                sslSocket.setNeedClientAuth(true);
            }
            return sslSocket;
        }
    };
    if (sslContextService != null) {
        smtpServer.setEnableTLS(true);
    } else {
        smtpServer.setHideTLS(true);
    }
    smtpServer.setSoftwareName("Apache NiFi SMTP");
    smtpServer.setPort(port);
    smtpServer.setMaxConnections(context.getProperty(SMTP_MAXIMUM_CONNECTIONS).asInteger());
    smtpServer.setMaxMessageSize(maxMessageSize);
    smtpServer.setConnectionTimeout(context.getProperty(SMTP_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    if (context.getProperty(SMTP_HOSTNAME).isSet()) {
        smtpServer.setHostName(context.getProperty(SMTP_HOSTNAME).getValue());
    }
    return smtpServer;
}
 
Example #25
Source File: MockSMTPServer.java    From james-project with Apache License 2.0 4 votes vote down vote up
private MockSMTPServer(SMTPBehaviorRepository behaviorRepository, ReceivedMailRepository mailRepository, int port) {
    this.server = new SMTPServer(ctx -> new MockMessageHandler(mailRepository, behaviorRepository));
    this.server.setPort(port);
}
 
Example #26
Source File: Wiser.java    From subethasmtp with Apache License 2.0 4 votes vote down vote up
/**
 * @return the server implementation
 */
public SMTPServer getServer()
{
	return this.server;
}
 
Example #27
Source File: SmtpServerImpl.java    From fake-smtp-server with Apache License 2.0 4 votes vote down vote up
SmtpServerImpl(SMTPServer smtpServer) {
    this.smtpServer = smtpServer;
}
 
Example #28
Source File: HoldMailSMTPServerTest.java    From holdmail with Apache License 2.0 3 votes vote down vote up
@Test
public void shouldStopServer() throws Exception{

    SMTPServer smtpServerMock = mock(SMTPServer.class);
    whenNew(SMTPServer.class).withArguments(smtpHandlerFactoryMock).thenReturn(smtpServerMock);

    holdMailSMTPServer.startup();
    holdMailSMTPServer.shutdown();

    verify(smtpServerMock).stop();

}
 
Example #29
Source File: HoldMailSMTPServerTest.java    From holdmail with Apache License 2.0 3 votes vote down vote up
@Test
public void shouldStartServer() throws Exception{

    SMTPServer smtpServerMock = mock(SMTPServer.class);
    whenNew(SMTPServer.class).withArguments(smtpHandlerFactoryMock).thenReturn(smtpServerMock);

    holdMailSMTPServer.startup();

    verify(smtpServerMock).setSoftwareName("HoldMailSMTPServer SMTP");
    verify(smtpServerMock).setPort(0);
    verify(smtpServerMock).start();

}
 
Example #30
Source File: SakaiMessageHandlerTest.java    From sakai with Educational Community License v2.0 2 votes vote down vote up
/**
 * Just creates a client connected to the test server.
 *
 * @return A connected client.
 * @throws IOException If it failed to connecto to the server.
 */
public SmartClient createClient() throws IOException {
    SMTPServer server = messageHandlerFactory.getServer();
    return new SmartClient("localhost", server.getPort(), "test");
}