1 13 package info.magnolia.cms.mail.commands; 14 15 import info.magnolia.cms.mail.MailConstants; 16 import info.magnolia.cms.mail.MgnlMailFactory; 17 import info.magnolia.cms.mail.handlers.MgnlMailHandler; 18 import info.magnolia.cms.mail.templates.MailAttachment; 19 import info.magnolia.cms.mail.templates.MgnlEmail; 20 21 import java.util.Arrays ; 22 23 import org.apache.commons.chain.Command; 24 import org.apache.commons.chain.Context; 25 import org.apache.commons.lang.StringUtils; 26 import org.slf4j.Logger; 27 import org.slf4j.LoggerFactory; 28 29 30 35 public class MailCommand implements Command { 36 37 static Logger log = LoggerFactory.getLogger(MailCommand.class); 38 39 public boolean execute(Context ctx) { 40 if (log.isDebugEnabled()) { 41 log.debug("starting sending mail"); 42 } 43 44 try { 45 MgnlMailFactory factory = MgnlMailFactory.getInstance(); 46 MgnlMailHandler handler = factory.getEmailHandler(); 47 48 if (log.isDebugEnabled()) 49 log.debug(Arrays.asList(ctx.entrySet().toArray()).toString()); 50 51 String template = (String ) ctx.get(MailConstants.ATTRIBUTE_TEMPLATE); 52 String to = (String ) ctx.get(MailConstants.ATTRIBUTE_TO); 53 String cc = (String ) ctx.get(MailConstants.ATTRIBUTE_CC); 54 55 if (StringUtils.isNotEmpty(template)) { 56 log.info("Command using mail template: " + template); 57 MgnlEmail email = factory.getEmailFromTemplate(template, ctx); 58 email.setToList(factory.convertEmailList(to)); 59 email.setCcList(factory.convertEmailList(cc)); 60 handler.prepareAndSendMail(email); 61 } 62 else { 63 log.info("command using static parameters"); 64 String from = (String ) ctx.get(MailConstants.ATTRIBUTE_FROM); 65 String type = (String ) ctx.get(MailConstants.ATTRIBUTE_TYPE); 66 String subject = (String ) ctx.get(MailConstants.ATTRIBUTE_SUBJECT); 67 String text = (String ) ctx.get(MailConstants.ATTRIBUTE_TEXT); 68 MailAttachment attachment = (MailAttachment) ctx.get(MailConstants.ATTRIBUTE_ATTACHMENT); 69 70 MgnlEmail email = factory.getEmailFromType(type); 71 email.setFrom(from); 72 email.setSubject(subject); 73 email.setToList(factory.convertEmailList(to)); 74 email.setBody(text, ctx); 75 if (attachment != null) { 76 email.addAttachment(attachment); 77 } 78 email.setCcList(factory.convertEmailList(cc)); 79 handler.prepareAndSendMail(email); 80 } 81 82 log.info("send mail successfully to:" + to); 83 } 84 catch (Exception e) { 85 log.error("Could not send email:" + e.getMessage()); 86 } 87 88 return false; 89 } 90 91 } 92 | Popular Tags |