forked from actframework/actframework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMailerConfig.java
More file actions
334 lines (300 loc) · 10.9 KB
/
MailerConfig.java
File metadata and controls
334 lines (300 loc) · 10.9 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
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
package act.mail;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* 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.
* #L%
*/
import act.app.App;
import act.app.AppHolderBase;
import org.osgl.exception.ConfigurationException;
import org.osgl.http.H;
import org.osgl.logging.LogManager;
import org.osgl.logging.Logger;
import org.osgl.util.C;
import org.osgl.util.E;
import org.osgl.util.S;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.util.*;
public class MailerConfig extends AppHolderBase {
public static final Logger logger = LogManager.get(MailerConfig.class);
public static final String FROM = "from";
public static final String CONTENT_TYPE = "content_type";
public static final String LOCALE = "locale";
public static final String SUBJECT = "subject";
public static final String TO = "to";
public static final String CC = "cc";
public static final String BCC = "bcc";
public static final String SMTP_HOST = "smtp.host";
public static final String SMTP_PORT = "smtp.port";
public static final String SMTP_TLS = "smtp.tls";
public static final String SMTP_SSL = "smtp.ssl";
public static final String SMTP_USERNAME = "smtp.username";
public static final String SMTP_PASSWORD = "smtp.password";
private String id;
private boolean isDefault;
private boolean mock;
private InternetAddress from;
private H.Format contentType;
private Locale locale;
private String subject;
private String host;
private String port;
private boolean useTls;
private boolean useSsl;
private String username;
private String password;
private List<InternetAddress> toList;
private List<InternetAddress> ccList;
private List<InternetAddress> bccList;
private volatile Session session;
public MailerConfig(String id, Map<String, String> properties, App app) {
super(app);
E.illegalArgumentIf(S.blank(id), "mailer config id expected");
this.id = id;
this.isDefault = "default".equals(id);
this.from = getFromConfig(properties);
this.contentType = getContentTypeConfig(properties);
this.locale = getLocaleConfig(properties);
this.subject = getProperty(SUBJECT, properties);
this.host = getProperty(SMTP_HOST, properties);
if ("gmail".equals(this.host)) {
this.host = "smtp.gmail.com";
}
this.username = getProperty(SMTP_USERNAME, properties);
if (null == host) {
if (S.notBlank(this.username) && this.username.endsWith("gmail.com")) {
this.host = "smtp.gmail.com";
} else {
logger.warn("smtp host configuration not found, will use mock smtp to send email");
mock = true;
}
}
if (!mock) {
this.useTls = getBooleanConfig(SMTP_TLS, properties) || S.eq("smtp.gmail.com", this.host);
this.useSsl = !this.useTls && getBooleanConfig(SMTP_SSL, properties);
this.port = getPortConfig(properties);
this.password = getProperty(SMTP_PASSWORD, properties);
if (null == username || null == password) {
logger.warn("Either smtp.username or smtp.password is not configured for mailer[%s]", id);
}
}
this.toList = getEmailListConfig(TO, properties);
this.ccList = getEmailListConfig(CC, properties);
this.bccList = getEmailListConfig(BCC, properties);
}
private String getProperty(String key, Map<String, String> properties) {
String key0 = key;
key = S.concat("mailer.", id, ".", key);
String val = properties.get(key);
if (null != val) {
return val;
}
String key2 = "act." + key;
val = properties.get(key2);
if (null != val) {
return val;
}
if (isDefault) {
key = S.concat("mailer.", key0);
val = properties.get(key);
if (null != val) {
return val;
}
return properties.get(S.concat("act.", key));
} else {
return null;
}
}
private List<InternetAddress> getEmailListConfig(String key, Map<String, String> properties) {
String s = getProperty(key, properties);
if (S.blank(s)) {
return C.list();
}
List<InternetAddress> l = new ArrayList<>();
return MailerContext.canonicalRecipients(l, s);
}
private String getPortConfig(Map<String, String> properties) {
String port = getProperty(SMTP_PORT, properties);
if (null == port) {
if (!useSsl && !useTls) {
port = "25";
} else if (useSsl) {
port = "465";
} else {
port = "587";
}
logger.warn("No smtp.port found for mailer[%s] configuration will use the default number: ", id, port);
} else {
try {
Integer.parseInt(port);
} catch (Exception e) {
throw E.invalidConfiguration("Invalid port configuration for mailer[%]: %s", id, port);
}
}
return port;
}
private boolean getBooleanConfig(String key, Map<String, String> properties) {
String s = getProperty(key, properties);
return null != s && Boolean.parseBoolean(s);
}
private Locale getLocaleConfig(Map<String, String> properties) {
String s = getProperty(LOCALE, properties);
if (null == s) {
return app().config().locale();
} else {
// the following code credit to
// http://www.java2s.com/Code/Java/Network-Protocol/GetLocaleFromString.htm
String localeString = s.trim();
if (localeString.toLowerCase().equals("default")) {
return app().config().locale();
}
// Extract language
int languageIndex = localeString.indexOf('_');
String language = null;
if (languageIndex == -1) {
// No further "_" so is "{language}" only
return new Locale(localeString, "");
} else {
language = localeString.substring(0, languageIndex);
}
// Extract country
int countryIndex = localeString.indexOf('_', languageIndex + 1);
String country;
if (countryIndex == -1) {
// No further "_" so is "{language}_{country}"
country = localeString.substring(languageIndex + 1);
return new Locale(language, country);
} else {
// Assume all remaining is the variant so is "{language}_{country}_{variant}"
country = localeString.substring(languageIndex + 1, countryIndex);
String variant = localeString.substring(countryIndex + 1);
return new Locale(language, country, variant);
}
}
}
private H.Format getContentTypeConfig(Map<String, String> properties) {
String s = getProperty(CONTENT_TYPE, properties);
if (null == s) {
return null;
}
try {
H.Format fmt = H.Format.valueOf(s);
if (H.Format.HTML == fmt || H.Format.TXT == fmt) {
return fmt;
}
throw E.invalidConfiguration("Content type not supported by mailer: %s", fmt);
} catch (ConfigurationException e) {
throw e;
} catch (Exception e) {
throw E.invalidConfiguration("Invalid mailer config content type: %s", s);
}
}
private InternetAddress getFromConfig(Map<String, String> properties) {
String s = getProperty(FROM, properties);
if (null == s) {
return null;
}
try {
InternetAddress[] ia = InternetAddress.parse(s);
if (null == ia || ia.length == 0) return null;
return ia[0];
} catch (AddressException e) {
throw E.invalidConfiguration(e, "invalid mailer from address: %s", s);
}
}
@Override
protected void releaseResources() {
if (null != session) {
session = null;
}
}
public String id() {
return id;
}
public String subject() {
return subject;
}
public H.Format contentType() {
return contentType;
}
public InternetAddress from() {
return from;
}
public String username() {
return username;
}
public String password() {
return password;
}
public Locale locale() {
return (null != locale) ? locale : app().config().locale();
}
public List<InternetAddress> to() {
return toList;
}
public List<InternetAddress> ccList() {
return ccList;
}
public List<InternetAddress> bccList() {
return bccList;
}
public boolean mock() {
return mock;
}
public Session session() {
if (null == session) {
synchronized (this) {
if (null == session) {
session = createSession();
}
}
}
return session;
}
private Session createSession() {
Properties p = new Properties();
if (mock()) {
p.setProperty("mail.smtp.host", "unknown");
p.setProperty("mail.smtp.port", "465");
} else {
p.setProperty("mail.smtp.host", host);
p.setProperty("mail.smtp.port", port);
}
if (null != username && null != password) {
if (useTls) {
p.put("mail.smtp.starttls.enable", "true");
} else if (useSsl) {
p.put("mail.smtp.socketFactory.port", port);
p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
p.setProperty("mail.smtp.auth", "true");
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
};
return Session.getInstance(p, auth);
} else {
return Session.getInstance(p);
}
}
}