summaryrefslogtreecommitdiffstats
path: root/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/mail/SmtpMailer.java
blob: d7859f3c4757cdda13fe0de0b2546c725698aac6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package org.openslx.bwlp.sat.mail;

import java.io.IOException;
import java.io.PrintStream;
import java.io.Writer;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.security.auth.login.LoginException;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.smtp.AuthenticatingSMTPClient;
import org.apache.commons.net.smtp.AuthenticatingSMTPClient.AUTH_METHOD;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openslx.util.Util;

public class SmtpMailer {

	// TODO Logging
	private static final Logger LOGGER = LogManager.getLogger(SmtpMailer.class);

	public enum EncryptionMode {
		NONE,
		IMPLICIT,
		EXPLICIT
	}

	private final String fromAddress;
	private final String fromName;
	private final String replyTo;
	private final AuthenticatingSMTPClient client;

	public SmtpMailer(String host, int port, EncryptionMode ssl, String fromAddress, String fromName,
			String replyTo, String username, String password, PrintStream logStream)
			throws UnknownHostException, SocketException, IOException, LoginException, InvalidKeyException,
			NoSuchAlgorithmException, InvalidKeySpecException {
		InetAddress[] ips = InetAddress.getAllByName(host);
		if (ips == null || ips.length == 0)
			throw new UnknownHostException(host);
		LOGGER.debug("Mailing via " + host + ", " + ssl);
		if (ssl == EncryptionMode.EXPLICIT || ssl == EncryptionMode.NONE) {
			client = new AuthenticatingSMTPClient("TLSv1.2", false, "UTF-8");
		} else {
			client = new AuthenticatingSMTPClient("TLSv1.2", true, "UTF-8");
		}
		boolean cleanup = true;
		try {
			if (logStream != null) {
				client.addProtocolCommandListener(new PrintCommandListener(logStream));
			}
			client.setConnectTimeout(5000);
			client.setDefaultTimeout(10000);
			IOException conEx = null;
			for (InetAddress ip : ips) {
				try {
					client.connect(ip, port);
					if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
						client.disconnect();
						continue;
					}
					conEx = null;
					break;
				} catch (IOException e) {
					conEx = e;
				}
			}
			if (conEx != null)
				throw conEx;
			if (!client.elogin("bwlehrpool.sat")) {
				throw new LoginException("SMTP server rejected EHLO");
			}
			if (ssl == EncryptionMode.EXPLICIT && !client.execTLS()) {
				throw new LoginException("STARTTLS (explicit TLS) failed");
			}
			if (!Util.isEmptyString(username)) {
				boolean authed = false;
				try {
					authed = client.auth(AUTH_METHOD.CRAM_MD5, username, password);
				} catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException e) {
					e.printStackTrace();
				}
				if (!authed && !client.auth(AUTH_METHOD.PLAIN, username, password)) {
					throw new LoginException("Server rejected AUTH command. Invalid username or password?");
				}
			}
			cleanup = false;
			this.fromAddress = fromAddress;
			this.fromName = fromName;
			this.replyTo = replyTo;
		} finally {
			if (cleanup)
				cleanup();
		}
	}

	private void cleanup() {
		try {
			client.logout();
		} catch (Exception e) {
		}
		try {
			client.disconnect();
		} catch (Exception e) {
		}
	}

	private void abort() throws IOException {
		if (!client.reset())
			throw new IOException("Cannot abort current mail transaction");
	}

	public boolean send(String recipient, String subject, String message, String listId) {
		Writer writer;
		SimpleSMTPHeader header;

		try {
			header = new QuotingSmtpHeader(fromAddress, fromName, recipient, subject);
			if (!Util.isEmptyString(replyTo)) {
				header.addHeaderField("Reply-To", replyTo);
			}
			if (!Util.isEmptyString(listId)) {
				header.addHeaderField("List-Id", listId);
				header.addHeaderField("Precedence", "bulk");
				header.addHeaderField("Auto-Submitted", "auto-generated");
			}
			header.addHeaderField("Content-Type", "text/plain; charset=utf-8");
			header.addHeaderField("Content-Transfer-Encoding", "8bit");

			if (!client.setSender(fromAddress)) {
				abort();
				return false;
			}
			if (!client.addRecipient(recipient)) {
				abort();
				return false;
			}
			writer = client.sendMessageData();
			if (writer == null) {
				abort();
				return false;
			}

			writer.write(header.toString());
			writer.write(message);
			writer.close();
			client.completePendingCommand();

			return true;
		} catch (IOException e) {
			cleanup();
			return false;
		}
	}

	public boolean isConnected() {
		if (!client.isConnected())
			return false;
		try {
			client.sendNoOp();
			return true;
		} catch (IOException e) {
			return false;
		}
	}

	public void close() {
		if (client.isConnected()) {
			try {
				client.logout();
			} catch (Exception e) { // Don't care
			}
			try {
				client.disconnect();
			} catch (Exception e) { // Don't care
			}
		}
	}

}