-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSendEmailTask.java
More file actions
188 lines (164 loc) · 7.36 KB
/
SendEmailTask.java
File metadata and controls
188 lines (164 loc) · 7.36 KB
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
/*-
* ========================LICENSE_START=================================
* ermes-mail
* %%
* Copyright (C) 2021 - 2025 SoftInstigate srl
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package com.softinstigate.ermes.mail;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
/**
* Runnable class to invoke the email.send() method in a thread
*/
public class SendEmailTask implements Callable<List<String>> {
private static final Logger LOGGER = Logger.getLogger(SendEmailTask.class.getName());
private final SMTPConfig smtpConfig;
private final EmailModel model;
private final String charset;
private final HtmlEmailFactory emailFactory;
/**
* Default constructor
*
* @param smtpConfig a SMTPConfig object
* @param model a EmailModel object
* @param charset a charset (default is UTF-8)
*/
public SendEmailTask(SMTPConfig smtpConfig, EmailModel model, String charset) {
this(smtpConfig, model, charset, new DefaultHtmlEmailFactory());
}
/**
* Constructor used for tests to inject a mock HtmlEmail factory.
*/
public SendEmailTask(SMTPConfig smtpConfig, EmailModel model, String charset, HtmlEmailFactory emailFactory) {
this.smtpConfig = smtpConfig;
this.model = model;
this.charset = charset;
this.emailFactory = emailFactory;
}
/**
* Constructor with UTF-8 charset
*
* @param smtpConfig a SMTPConfig object
* @param model a EmailModel object
*/
public SendEmailTask(SMTPConfig smtpConfig, EmailModel model) {
this(smtpConfig, model, "UTF-8");
}
/**
* Send the EmailModel using an Apache Commons' HtmlEmail instance
*
* @return a {@code Future<List<String>>} of errors.
*/
@Override
public List<String> call() {
LOGGER.info("Processing " + model.toSecureString());
final List<String> errors = new ArrayList<>();
// Begin FIX for javax.activation.UnsupportedDataTypeException: no object DCH
// for MIME type multipart/alternative;
setDefaultCommandMap();
Thread.currentThread().setContextClassLoader(EmailService.class.getClassLoader());
// End Fix
HtmlEmail email = emailFactory.create();
try {
email.setCharset(charset);
email.setHostName(smtpConfig.hostname);
email.setSmtpPort(smtpConfig.port);
email.setAuthentication(smtpConfig.username, smtpConfig.password);
email.setSSLOnConnect(smtpConfig.ssl);
email.setSslSmtpPort(String.valueOf(smtpConfig.sslPort));
// Configure STARTTLS using Commons Email API (preferred to mutating Session properties).
// The security mode is expressed via SMTPConfig.SecurityMode and set by
// the factory methods on SMTPConfig (forPlain/forSsl/forStartTls*).
if (smtpConfig.securityMode == SMTPConfig.SecurityMode.STARTTLS_OPTIONAL
|| smtpConfig.securityMode == SMTPConfig.SecurityMode.STARTTLS_REQUIRED) {
email.setStartTLSEnabled(true);
if (smtpConfig.securityMode == SMTPConfig.SecurityMode.STARTTLS_REQUIRED) {
email.setStartTLSRequired(true);
}
}
email.setFrom(model.from, model.senderFullName);
email.setSubject(model.subject);
email.setHtmlMsg(model.message);
processAttachments(email, model, errors);
for (EmailModel.Recipient r : model.getToRecipients()) {
email.addTo(r.email, r.name);
}
for (EmailModel.Recipient r : model.getCcRecipients()) {
email.addCc(r.email, r.name);
}
for (EmailModel.Recipient r : model.getBccRecipients()) {
email.addBcc(r.email, r.name);
}
// Enable JavaMail debug if requested via system property (useful for integration tests)
boolean mailDebug = Boolean.getBoolean("mail.debug");
if (mailDebug) {
email.setDebug(true);
}
email.send();
LOGGER.info(String.format("Email successfully sent!\nTO: %s \nCC: %s \nBCC: %s", model.getToRecipients(),
model.getCcRecipients(), model.getBccRecipients()));
} catch (EmailException ex) {
LOGGER.log(Level.SEVERE, "Error sending email.", ex);
errors.add(ex.getMessage());
}
return errors;
}
/**
* Attach included attachments to email
*
* @param email a HtmlEmail instance
* @param model the EmailModel to process
*/
private void processAttachments(HtmlEmail email, EmailModel model, List<String> errors) {
for (EmailModel.Attachment attachment : model.getAttachments()) {
try {
EmailAttachment emailAttachment = new EmailAttachment();
emailAttachment.setDisposition(EmailAttachment.ATTACHMENT);
emailAttachment.setURL(URI.create(attachment.url).toURL());
emailAttachment.setName(attachment.fileName);
emailAttachment.setDescription(attachment.description);
email.attach(emailAttachment);
} catch (MalformedURLException ex) {
LOGGER.log(Level.SEVERE, String.format("Malformed attachment.url '%s'", attachment.url), ex);
errors.add(String.format("Malformed attachment.url '%s'", ex.getMessage()));
} catch (EmailException ex) {
LOGGER.log(Level.SEVERE, String.format("Error with attachment '%s'", attachment.toString()), ex);
errors.add(String.format("Error with attachment '%s'", ex.getMessage()));
}
}
}
/**
* Add explicit MailcapCommandMap (workaround - see https://stackoverflow.com/a/21183987)
*/
private void setDefaultCommandMap() {
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
}
}