1
1
package com .reedelk .mail .internal .smtp ;
2
2
3
3
import com .reedelk .mail .component .SMTPConfiguration ;
4
+ import com .reedelk .mail .component .smtp .SMTPProtocol ;
5
+ import com .reedelk .mail .internal .commons .Defaults ;
6
+ import com .reedelk .mail .internal .exception .MailMessageConfigurationException ;
4
7
import org .apache .commons .mail .DefaultAuthenticator ;
5
8
import org .apache .commons .mail .Email ;
6
9
7
- import javax . mail . Session ;
10
+ import java . util . Optional ;
8
11
9
12
public class MailSessionBuilder {
10
13
@@ -25,13 +28,26 @@ public MailSessionBuilder configuration(SMTPConfiguration configuration) {
25
28
}
26
29
27
30
public void build () {
28
- SMTPProperties smtpProperties = new SMTPProperties (configuration );
29
-
30
- String username = configuration .getUsername ();
31
- String password = configuration .getPassword ();
32
-
33
- Session session = Session .getInstance (smtpProperties , new DefaultAuthenticator (username , password ));
34
-
35
- email .setMailSession (session );
31
+ SMTPProtocol protocol = Optional .ofNullable (configuration .getProtocol ()).orElse (SMTPProtocol .SMTP );
32
+
33
+ String host = Optional .ofNullable (configuration .getHost ())
34
+ .orElseThrow (() -> new MailMessageConfigurationException ("Host is mandatory" ));
35
+
36
+ boolean startTlsEnable = Optional .ofNullable (configuration .getStartTlsEnabled ()).orElse (Defaults .TLS_ENABLE );
37
+ Integer connectionTimeout = Optional .ofNullable (configuration .getConnectTimeout ()).orElse (Defaults .CONNECT_TIMEOUT );
38
+ Integer socketTimeout = Optional .ofNullable (configuration .getSocketTimeout ()).orElse (Defaults .SOCKET_TIMEOUT );
39
+
40
+ email .setHostName (host );
41
+ email .setSmtpPort (configuration .getPort ());
42
+ email .setSocketTimeout (socketTimeout );
43
+ email .setSocketConnectionTimeout (connectionTimeout );
44
+ email .setAuthenticator (new DefaultAuthenticator (configuration .getUsername (), configuration .getPassword ()));
45
+ if (SMTPProtocol .SMTPS .equals (protocol )) {
46
+ email .setSSLOnConnect (true );
47
+ email .setSslSmtpPort (Integer .toString (configuration .getPort ()));
48
+ }
49
+ if (startTlsEnable ) {
50
+ email .setStartTLSEnabled (configuration .getStartTlsEnabled ());
51
+ }
36
52
}
37
53
}
0 commit comments