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 package info.magnolia.module.mail.commands;
35
36 import info.magnolia.context.WebContext;
37 import info.magnolia.cms.util.AlertUtil;
38 import info.magnolia.module.mail.MailModule;
39 import info.magnolia.module.mail.MailTemplate;
40 import info.magnolia.module.mail.MgnlMailFactory;
41 import info.magnolia.module.mail.templates.MailAttachment;
42 import info.magnolia.module.mail.templates.MgnlEmail;
43 import info.magnolia.module.mail.util.MailUtil;
44
45 import java.util.Arrays;
46 import java.util.List;
47 import java.util.Map;
48
49 import org.apache.commons.chain.Command;
50 import org.apache.commons.chain.Context;
51 import org.apache.commons.lang.StringUtils;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55
56
57
58
59
60
61 public class MailCommand implements Command {
62
63 public static Logger log = LoggerFactory.getLogger(MailCommand.class);
64
65 public boolean execute(Context ctx) {
66 if (log.isDebugEnabled()) {
67 log.debug("starting sending mail");
68 }
69
70 try {
71 MgnlMailFactory factory = MailModule.getInstance().getFactory();
72 MgnlEmail email;
73 if (log.isDebugEnabled())
74 log.debug(Arrays.asList(ctx.entrySet().toArray()).toString());
75
76 String template = (String) ctx.get("mailTemplate");
77
78 if(ctx.containsKey(MailTemplate.MAIL_PARAMETERS)) {
79 Map<String, String> temp = MailUtil.convertToMap((String)ctx.get(MailTemplate.MAIL_PARAMETERS));
80 ctx.putAll(temp);
81 }
82
83
84 List<MailAttachment> attachments = null;
85
86 if(ctx instanceof WebContext) {
87 attachments = MailUtil.createAttachmentList(((WebContext)ctx).getParameters());
88 }
89
90 if (StringUtils.isNotEmpty(template)) {
91 log.debug("Command using mail template: " + template);
92
93 email = factory.getEmailFromTemplate(template, attachments, ctx);
94 email.setBodyFromResourceFile();
95 }
96 else {
97 log.debug("command using static parameters");
98
99 email = factory.getEmail(ctx, attachments);
100 if(StringUtils.isEmpty(email.getTemplate().getTemplateFile())) {
101 email.setBody();
102 } else {
103 email.setBodyFromResourceFile();
104 }
105
106 }
107 factory.getEmailHandler().sendMail(email);
108
109 log.info("send mail successfully to:" + email.getTemplate().getTo());
110 }
111 catch (Exception e) {
112 log.debug("Could not send email:" + e.getMessage(), e);
113 log.error("Could not send email:" + e.getMessage());
114 AlertUtil.setMessage("Error: " + e.getMessage());
115 return false;
116 }
117
118 return true;
119 }
120
121 }