Repository navigation
Expand file tree
/
Copy pathMailerContext.java
More file actions
349 lines (298 loc) · 10.2 KB
/
Copy pathMailerContext.java
File metadata and controls
349 lines (298 loc) · 10.2 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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package act.mail;
import act.Act;
import act.app.App;
import act.util.ActContext;
import act.view.Template;
import act.view.ViewManager;
import org.osgl.$;
import org.osgl.concurrent.ContextLocal;
import org.osgl.http.H;
import org.osgl.storage.ISObject;
import org.osgl.storage.impl.SObject;
import org.osgl.util.C;
import org.osgl.util.E;
import org.osgl.util.S;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.*;
import static act.app.App.logger;
public class MailerContext extends ActContext.ActContextBase<MailerContext> {
private H.Format fmt = H.Format.HTML;
private InternetAddress from;
private String subject;
private List<InternetAddress> to = C.newList();
private List<InternetAddress> cc = C.newList();
private List<InternetAddress> bcc = C.newList();
private String confId;
private List<ISObject> attachments = C.newList();
private String senderPath; // e.g. com.mycorp.myapp.mailer.AbcMailer.foo
private static final ContextLocal<MailerContext> _local = $.contextLocal();
public MailerContext(App app, String confId) {
super(app);
this.confId = confId;
_local.set(this);
}
@Override
protected void releaseResources() {
super.releaseResources();
to.clear();
cc.clear();
bcc.clear();
_local.remove();
}
public MailerContext configId(String id) {
confId = id;
return this;
}
public String senderPath() {
return senderPath;
}
public MailerContext senderPath(String path) {
senderPath = path;
return this;
}
public MailerContext senderPath(String className, String methodName) {
senderPath = S.builder(className).append(".").append(methodName).toString();
return this;
}
public MailerConfig mailerConfig() {
return app().mailerConfigManager().config(confId);
}
@Override
public MailerContext accept(H.Format fmt) {
E.NPE(fmt);
this.fmt = fmt;
return this;
}
@Override
public H.Format accept() {
return null != fmt ? fmt : mailerConfig().contentType();
}
/**
* If {@link #templatePath(String) template path has been set before} then return
* the template path. Otherwise returns the {@link #senderPath()}
* @return either template path or action path if template path not set before
*/
public String templatePath() {
String path = super.templatePath();
if (S.notBlank(path)) {
return path;
} else {
return senderPath().replace('.', '/');
}
}
@Override
public MailerContext templatePath(String templatePath) {
return super.templatePath(templatePath);
}
@Override
public <T> T renderArg(String name) {
return super.renderArg(name);
}
@Override
public MailerContext renderArg(String name, Object val) {
return super.renderArg(name, val);
}
@Override
public Map<String, Object> renderArgs() {
return super.renderArgs();
}
/**
* Called by bytecode enhancer to set the name list of the render arguments that is update
* by the enhancer
* @param names the render argument names separated by ","
* @return this AppContext
*/
public MailerContext __appRenderArgNames(String names) {
return renderArg("__arg_names__", C.listOf(names.split(",")));
}
public List<String> __appRenderArgNames() {
return renderArg("__arg_names__");
}
public H.Format contentType() {
return accept();
}
public String subject() {
return null != subject ? subject : mailerConfig().subject();
}
public MailerContext subject(String subject) {
this.subject = subject;
return this;
}
@Override
public Locale locale() {
return config().locale();
}
public MailerContext attach(ISObject... sobjs) {
attachments.addAll(C.listOf(sobjs));
return this;
}
public MailerContext attach(File... files) {
for (File file : files) {
attachments.add(SObject.of(file));
}
return this;
}
public MailerContext from(String from) {
E.illegalArgumentIf(S.empty(from), "<from> cannot be empty");
List<InternetAddress> l = canonicalRecipients(null, from);
E.illegalArgumentIf(l.isEmpty(), "from address expected");
if (l.size() > 1) {
logger.warn("There are more than one email address specified, only the first one will be used as From address");
}
this.from = l.get(0);
return this;
}
public InternetAddress from() {
if (null == from) {
return mailerConfig().from();
}
return from;
}
/**
* Set to recipients
*
* @param recipients the list of emails
* @return this mailer context
*/
public MailerContext to(String... recipients) {
to = canonicalRecipients(null, recipients);
return this;
}
public List<InternetAddress> to() {
return to.isEmpty() ? mailerConfig().to() : to;
}
public MailerContext cc(String... recipients) {
cc = canonicalRecipients(null, recipients);
return this;
}
public List<InternetAddress> cc() {
return cc.isEmpty() ? mailerConfig().ccList() : cc;
}
public MailerContext bcc(String... recipients) {
bcc = canonicalRecipients(null, recipients);
return this;
}
public List<InternetAddress> bcc() {
return bcc.isEmpty() ? mailerConfig().bccList() : bcc;
}
public MailerContext addTo(String... recipients) {
canonicalRecipients(to, recipients);
return this;
}
public MailerContext addCc(String... recipients) {
canonicalRecipients(cc, recipients);
return this;
}
public MailerContext addBcc(String... recipients) {
canonicalRecipients(bcc, recipients);
return this;
}
public boolean send() {
try {
MimeMessage message = createMessage();
if (!mailerConfig().mock()) {
Transport.send(message);
} else {
logger.info("Sending email\n%sEnd email\n", debug(message));
}
return true;
} catch (Exception e) {
logger.error(e, "Error sending email: %s", this);
return false;
}
}
private String debug(MimeMessage msg) throws Exception {
List<String> lines = C.newList();
lines.add(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n>> recipients");
Address[] aa = msg.getAllRecipients();
if (null != aa) {
for (Address a: aa) {
lines.add(a.getType() + ":" + a.toString());
}
} else {
lines.add("[ERROR] no recipients defined");
}
lines.add(">> header lines");
Enumeration e = msg.getAllHeaderLines();
while (e.hasMoreElements()) {
lines.add(S.string(e.nextElement()));
}
Object content = msg.getContent();
if (content instanceof Multipart) {
lines.add(">> multipart content");
Multipart mp = (Multipart)content;
for (int i = 0; i < mp.getCount(); ++i) {
MimeBodyPart bp = (MimeBodyPart)mp.getBodyPart(i);
lines.add(S.fmt(">>> #%s [%s]", i, bp.getContentType()));
String fileName = bp.getFileName();
if (S.notBlank(fileName)) {
lines.add("file: " + fileName);
} else {
lines.add(S.string(bp.getContent()));
}
}
} else {
lines.add(">> content[" + msg.getContentType() + "]");
lines.add(S.string(msg.getContent()));
}
lines.add("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
return S.join("\n", lines);
}
private MimeMessage createMessage() throws Exception {
MailerConfig config = mailerConfig();
if (null == config) {
throw E.unexpected("Cannot find mailer config for %s", confId);
}
Session session = mailerConfig().session();
MimeMessage msg = new MimeMessage(session);
msg.setFrom(from());
msg.setSubject(subject());
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, list2Array(to()));
msg.setRecipients(Message.RecipientType.CC, list2Array(cc()));
msg.setRecipients(Message.RecipientType.BCC, list2Array(bcc()));
ViewManager vm = Act.viewManager();
Template t = vm.load(this);
E.illegalStateIf(null == t, "Mail template not defined");
String content = t.render(this);
if (attachments.isEmpty()) {
msg.setText(content, config().encoding(), accept().name());
} else {
Multipart mp = new MimeMultipart();
MimeBodyPart bp = new MimeBodyPart();
mp.addBodyPart(bp);
bp.setText(content, config().encoding(), accept().name());
for (ISObject sobj : attachments) {
MimeBodyPart attachment = new MimeBodyPart();
attachment.attachFile(sobj.asFile(), sobj.getAttribute(ISObject.ATTR_CONTENT_TYPE), "utf-8");
mp.addBodyPart(attachment);
}
msg.setContent(mp);
}
msg.saveChanges();
return msg;
}
private static InternetAddress[] list2Array(List<InternetAddress> list) {
int len = list.size();
InternetAddress[] array = new InternetAddress[len];
return list.toArray(array);
}
private static final String SEP = "[;:,]+";
public static MailerContext current() {
return _local.get();
}
public static List<InternetAddress> canonicalRecipients(List<InternetAddress> l, String... recipients) {
if (null == l) l = C.newList();
if (recipients.length == 0) return l;
String s = S.join(",", recipients).replaceAll(SEP, ",");
try {
InternetAddress[] aa = InternetAddress.parse(s);
l.addAll(C.listOf(aa));
return l;
} catch (AddressException e) {
throw E.unexpected(e);
}
}
}