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 @Override
66 public boolean execute(Context ctx) {
67 if (log.isDebugEnabled()) {
68 log.debug("starting sending mail");
69 }
70
71 try {
72 MgnlMailFactory factory = MailModule.getInstance().getFactory();
73 MgnlEmail email;
74 if (log.isDebugEnabled()) {
75 log.debug(Arrays.asList(ctx.entrySet().toArray()).toString());
76 }
77
78 String template = (String) ctx.get("mailTemplate");
79
80 if(ctx.containsKey(MailTemplate.MAIL_PARAMETERS)) {
81 Map<String, String> temp = MailUtil.convertToMap((String)ctx.get(MailTemplate.MAIL_PARAMETERS));
82 ctx.putAll(temp);
83 }
84
85
86 List<MailAttachment> attachments = null;
87
88 if(ctx instanceof WebContext) {
89 attachments = MailUtil.createAttachmentList(((WebContext)ctx).getParameters());
90 }
91
92 if (StringUtils.isNotEmpty(template)) {
93 log.debug("Command using mail template: " + template);
94
95 email = factory.getEmailFromTemplate(template, attachments, ctx);
96 email.setBodyFromResourceFile();
97 }
98 else {
99 log.debug("command using static parameters");
100
101 email = factory.getEmail(ctx, attachments);
102 if(StringUtils.isEmpty(email.getTemplate().getTemplateFile())) {
103 email.setBody();
104 } else {
105 email.setBodyFromResourceFile();
106 }
107
108 }
109 factory.getEmailHandler().sendMail(email);
110
111 log.info("send mail successfully to:" + email.getTemplate().getTo());
112 }
113 catch (Exception e) {
114 log.debug("Could not send email:" + e.getMessage(), e);
115 log.error("Could not send email:" + e.getMessage());
116 AlertUtil.setMessage("Error: " + e.getMessage());
117 return false;
118 }
119
120 return true;
121 }
122
123 }