-
Notifications
You must be signed in to change notification settings - Fork 188
/
MailTransport.java
373 lines (325 loc) · 18.5 KB
/
MailTransport.java
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
* Copyright (c) 2010-2013 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.notifications.impl.api.transports;
import static com.evolveum.midpoint.notifications.impl.api.transports.TransportUtil.formatToFileOld;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.annotation.PostConstruct;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.evolveum.midpoint.notifications.impl.TransportRegistry;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.evolveum.midpoint.notifications.api.NotificationManager;
import com.evolveum.midpoint.notifications.api.events.Event;
import com.evolveum.midpoint.notifications.api.transports.Message;
import com.evolveum.midpoint.notifications.api.transports.Transport;
import com.evolveum.midpoint.notifications.impl.NotificationFunctionsImpl;
import com.evolveum.midpoint.notifications.impl.util.MimeTypeUtil;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.crypto.Protector;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.repo.common.expression.ExpressionFactory;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.MiscSchemaUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.MailConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.MailServerConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.MailTransportSecurityType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.NotificationMessageAttachmentType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
import com.evolveum.prism.xml.ns._public.types_3.RawType;
/**
* @author mederly
*/
@Component
public class MailTransport implements Transport {
private static final Trace LOGGER = TraceManager.getTrace(MailTransport.class);
private static final String NAME = "mail";
private static final String DOT_CLASS = MailTransport.class.getName() + ".";
@Autowired
@Qualifier("cacheRepositoryService")
private transient RepositoryService cacheRepositoryService;
@Autowired
private Protector protector;
@Autowired
private NotificationManager notificationManager;
@Autowired
protected ExpressionFactory expressionFactory;
@Autowired private TransportRegistry transportRegistry;
@PostConstruct
public void init() {
transportRegistry.registerTransport(NAME, this);
}
@Override
public void send(Message mailMessage, String transportName, Event event, Task task, OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
result.addArbitraryObjectCollectionAsParam("mailMessage recipient(s)", mailMessage.getTo());
result.addParam("mailMessage subject", mailMessage.getSubject());
SystemConfigurationType systemConfiguration = NotificationFunctionsImpl.getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy"));
// if (systemConfiguration == null) {
// String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent.";
// LOGGER.warn(msg) ;
// result.recordWarning(msg);
// return;
// }
//
// MailConfigurationType mailConfigurationType = null;
// SecurityPolicyType securityPolicyType = NotificationFuctionsImpl.getSecurityPolicyConfiguration(systemConfiguration.getGlobalSecurityPolicyRef(), cacheRepositoryService, result);
// if (securityPolicyType != null && securityPolicyType.getAuthentication() != null && securityPolicyType.getAuthentication().getMailAuthentication() != null) {
// for (MailAuthenticationPolicyType mailAuthenticationPolicy : securityPolicyType.getAuthentication().getMailAuthentication()) {
// if (mailAuthenticationPolicy.getNotificationConfiguration() != null ){
// mailConfigurationType = mailAuthenticationPolicy.getNotificationConfiguration().getMail();
// }
// }
// }
if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null
|| systemConfiguration.getNotificationConfiguration().getMail() == null) {
String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent.";
LOGGER.warn(msg) ;
result.recordWarning(msg);
return;
}
MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail();
String logToFile = mailConfigurationType.getLogToFile();
if (logToFile != null) {
TransportUtil.logToFile(logToFile, formatToFileOld(mailMessage), LOGGER);
}
String redirectToFile = mailConfigurationType.getRedirectToFile();
int optionsForFilteringRecipient = TransportUtil.optionsForFilteringRecipient(mailConfigurationType);
List<String> allowedRecipientTo = new ArrayList<String>();
List<String> forbiddenRecipientTo = new ArrayList<String>();
List<String> allowedRecipientCc = new ArrayList<String>();
List<String> forbiddenRecipientCc = new ArrayList<String>();
List<String> allowedRecipientBcc = new ArrayList<String>();
List<String> forbiddenRecipientBcc = new ArrayList<String>();
if (optionsForFilteringRecipient != 0) {
TransportUtil.validateRecipient(allowedRecipientTo, forbiddenRecipientTo, mailMessage.getTo(), mailConfigurationType, task, result,
expressionFactory, MiscSchemaUtil.getExpressionProfile(), LOGGER);
TransportUtil.validateRecipient(allowedRecipientCc, forbiddenRecipientCc, mailMessage.getCc(), mailConfigurationType, task, result,
expressionFactory, MiscSchemaUtil.getExpressionProfile(), LOGGER);
TransportUtil.validateRecipient(allowedRecipientBcc, forbiddenRecipientBcc, mailMessage.getBcc(), mailConfigurationType, task, result,
expressionFactory, MiscSchemaUtil.getExpressionProfile(), LOGGER);
if (redirectToFile != null) {
if(!forbiddenRecipientTo.isEmpty() || !forbiddenRecipientCc.isEmpty() || !forbiddenRecipientBcc.isEmpty()) {
mailMessage.setTo(forbiddenRecipientTo);
mailMessage.setCc(forbiddenRecipientCc);
mailMessage.setBcc(forbiddenRecipientBcc);
TransportUtil.appendToFile(redirectToFile, formatToFileOld(mailMessage), LOGGER, result);
}
mailMessage.setTo(allowedRecipientTo);
mailMessage.setCc(allowedRecipientCc);
mailMessage.setBcc(allowedRecipientBcc);
}
} else if (redirectToFile != null) {
TransportUtil.appendToFile(redirectToFile, formatToFileOld(mailMessage), LOGGER, result);
return;
}
if (optionsForFilteringRecipient != 0 && mailMessage.getTo().isEmpty()) {
String msg = "No recipient found after recipient validation.";
LOGGER.debug(msg) ;
result.recordSuccess();
return;
}
if (mailConfigurationType.getServer().isEmpty()) {
String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo() + " will not be sent.";
LOGGER.warn(msg) ;
result.recordWarning(msg);
return;
}
long start = System.currentTimeMillis();
String defaultFrom = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom() : "nobody@nowhere.org";
for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) {
OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer");
final String host = mailServerConfigurationType.getHost();
resultForServer.addContext("server", host);
resultForServer.addContext("port", mailServerConfigurationType.getPort());
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
if (mailServerConfigurationType.getPort() != null) {
properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort()));
}
MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType.getTransportSecurity();
boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false;
if (mailTransportSecurityType != null) {
switch (mailTransportSecurityType) {
case STARTTLS_ENABLED:
starttlsEnable = true;
break;
case STARTTLS_REQUIRED:
starttlsEnable = true;
starttlsRequired = true;
break;
case SSL:
sslEnabled = true;
break;
}
}
properties.put("mail.smtp.ssl.enable", "" + sslEnabled);
properties.put("mail.smtp.starttls.enable", "" + starttlsEnable);
properties.put("mail.smtp.starttls.required", "" + starttlsRequired);
if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) {
properties.put("mail.debug", "true");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Using mail properties: ");
for (Object key : properties.keySet()) {
if (key instanceof String && ((String) key).startsWith("mail.")) {
LOGGER.debug(" - {} = {}", key, properties.get(key));
}
}
}
task.recordState("Sending notification mail via " + host);
Session session = Session.getInstance(properties);
try {
MimeMessage mimeMessage = new MimeMessage(session);
String from = mailMessage.getFrom() != null ? mailMessage.getFrom() : defaultFrom;
mimeMessage.setFrom(new InternetAddress(from));
for (String recipient : mailMessage.getTo()) {
mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));
}
for (String recipientCc : mailMessage.getCc()) {
mimeMessage.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(recipientCc));
}
for (String recipientBcc : mailMessage.getBcc()) {
mimeMessage.addRecipient(javax.mail.Message.RecipientType.BCC, new InternetAddress(recipientBcc));
}
mimeMessage.setSubject(mailMessage.getSubject(), "utf-8");
String contentType = mailMessage.getContentType();
if (StringUtils.isEmpty(contentType)) {
contentType = "text/plain; charset=UTF-8";
}
BodyPart messageBody = new MimeBodyPart();
messageBody.setContent(mailMessage.getBody(), contentType);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBody);
for(NotificationMessageAttachmentType attachment : mailMessage.getAttachments()) {
if(attachment.getContent() != null || attachment.getContentFromFile() != null) {
String fileName = null;
BodyPart attachmentBody = new MimeBodyPart();
if(attachment.getContent() != null) {
try {
Object content = RawType.getValue(attachment.getContent());
if(content == null) {
LOGGER.warn("RawType " + attachment.getContent() + " isn't possible to parse.");
return;
}
attachmentBody.setContent(content, attachment.getContentType());
} catch (SchemaException e) {
LOGGER.warn("RawType " + attachment.getContent() + " isn't possible to parse.");
return;
}
if(StringUtils.isBlank(attachment.getFileName())) {
fileName = "attachment";
} else {
fileName = attachment.getFileName();
}
} else {
if(!Files.isReadable(Paths.get(attachment.getContentFromFile()))) {
LOGGER.warn("File " + attachment.getContentFromFile() + " non exist or isn't readable.");
return;
}
DataSource source = new FileDataSource(attachment.getContentFromFile()) {
@Override
public String getContentType() {
return attachment.getContentType();
}
};
attachmentBody.setDataHandler(new DataHandler(source));
if(StringUtils.isBlank(attachment.getFileName())) {
fileName = source.getName();
} else {
fileName = attachment.getFileName();
}
}
if(!fileName.contains(".")) {
fileName += MimeTypeUtil.getDefaultExt(attachment.getContentType());
}
attachmentBody.setFileName(fileName);
if(!StringUtils.isBlank(attachment.getContentId())) {
attachmentBody.setHeader("Content-ID", attachment.getContentId());
}
multipart.addBodyPart(attachmentBody);
} else {
LOGGER.warn("NotificationMessageAttachmentType doesn't contain content.");
}
}
mimeMessage.setContent(multipart);
javax.mail.Transport t = session.getTransport("smtp");
try {
if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) {
ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword();
String password = null;
if (passwordProtected != null) {
try {
password = protector.decryptString(passwordProtected);
} catch (EncryptionException e) {
String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any.";
LoggingUtils.logException(LOGGER, msg, e);
resultForServer.recordFatalError(msg, e);
continue;
}
}
t.connect(mailServerConfigurationType.getUsername(), password);
} else {
t.connect();
}
t.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + ".");
resultForServer.recordSuccess();
result.recordSuccess();
long duration = System.currentTimeMillis() - start;
task.recordState("Notification mail sent successfully via " + host + ", in " + duration + " ms overall.");
task.recordNotificationOperation(NAME, true, duration);
} finally {
t.close();
}
return;
} catch (MessagingException e) {
String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", trying another mail server, if there is any";
LoggingUtils.logException(LOGGER, msg, e);
resultForServer.recordFatalError(msg, e);
task.recordState("Error sending notification mail via " + host);
}
}
LOGGER.warn("No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent.") ;
result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent.");
task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start);
}
private String formatToFile(Message mailMessage) {
return "============================================ " + "\n" +new Date() + "\n" + mailMessage.toString() + "\n\n";
}
@Override
public String getDefaultRecipientAddress(UserType recipient) {
return recipient.getEmailAddress();
}
@Override
public String getName() {
return NAME;
}
}