1 package com.nilhcem.fakesmtp.server;
2
3 import java.net.InetAddress;
4
5 import org.slf4j.Logger;
6 import org.slf4j.LoggerFactory;
7 import org.subethamail.smtp.helper.SimpleMessageListenerAdapter;
8 import org.subethamail.smtp.server.SMTPServer;
9 import com.nilhcem.fakesmtp.core.exception.BindPortException;
10 import com.nilhcem.fakesmtp.core.exception.OutOfRangePortException;
11
12
13
14
15
16
17
18 public enum SMTPServerHandler {
19 INSTANCE;
20
21 private static final Logger LOGGER = LoggerFactory.getLogger(SMTPServerHandler.class);
22 private final MailSaver mailSaver = new MailSaver();
23 private final MailListener myListener = new MailListener(mailSaver);
24 private final SMTPServer smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(myListener), new SMTPAuthHandlerFactory());
25
26 SMTPServerHandler() {
27 }
28
29
30
31
32
33
34
35
36
37
38 public void startServer(int port, InetAddress bindAddress) throws BindPortException, OutOfRangePortException {
39 LOGGER.debug("Starting server on port {}", port);
40 try {
41 smtpServer.setBindAddress(bindAddress);
42 smtpServer.setPort(port);
43 smtpServer.start();
44 } catch (RuntimeException exception) {
45 if (exception.getMessage().contains("BindException")) {
46 LOGGER.error("{}. Port {}", exception.getMessage(), port);
47 throw new BindPortException(exception, port);
48 } else if (exception.getMessage().contains("out of range")) {
49 LOGGER.error("Port {} out of range.", port);
50 throw new OutOfRangePortException(exception, port);
51 } else {
52 LOGGER.error("", exception);
53 throw exception;
54 }
55 }
56 }
57
58
59
60
61
62
63
64 public void stopServer() {
65 if (smtpServer.isRunning()) {
66 LOGGER.debug("Stopping server");
67 smtpServer.stop();
68 }
69 }
70
71
72
73
74
75
76 public MailSaver getMailSaver() {
77 return mailSaver;
78 }
79
80
81
82
83
84
85 public SMTPServer getSmtpServer() {
86 return smtpServer;
87 }
88 }