View Javadoc

1   /**
2    * This file Copyright (c) 2003-2011 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.module.mail.templates;
35  
36  import info.magnolia.module.mail.MailException;
37  import info.magnolia.module.mail.MailTemplate;
38  import info.magnolia.module.mail.util.MailUtil;
39  
40  import java.io.BufferedReader;
41  import java.io.File;
42  import java.io.FileReader;
43  import java.net.URL;
44  import java.util.ArrayList;
45  import java.util.List;
46  import java.util.regex.Matcher;
47  import java.util.regex.Pattern;
48  
49  import javax.mail.Address;
50  import javax.mail.Message;
51  import javax.mail.MessagingException;
52  import javax.mail.internet.AddressException;
53  import javax.mail.internet.InternetAddress;
54  import javax.mail.internet.MimeBodyPart;
55  import javax.mail.internet.MimeMessage;
56  
57  import org.apache.commons.io.IOUtils;
58  import org.apache.commons.lang.StringUtils;
59  import org.slf4j.Logger;
60  import org.slf4j.LoggerFactory;
61  
62  
63  /**
64   * Base class to send emails using Magnolia.
65   * Date: Mar 30, 2006 Time: 1:01:37 PM
66   * @author <a href="mailto:niko@macnica.com">Nicolas Modrzyk</a>
67   */
68  public abstract class MgnlEmail extends MimeMessage {
69  
70      protected static final String CONTENT_TYPE = "Content-Type";
71  
72      protected static final String TEXT_PLAIN_UTF = "text/plain; charset=UTF-8";
73  
74      protected static final String TEXT_HTML_UTF = "text/html; charset=UTF-8";
75  
76      protected static final String CHARSET_HEADER_STRING = "charset=";
77  
78      protected static final Pattern EMAIL_WITH_PERSONAL_PATTERN = Pattern.compile("\"+(.*)\"+<(.*)>");
79  
80      public static Logger log = LoggerFactory.getLogger(MgnlEmail.class);
81  
82      private MailTemplate template;
83  
84      private boolean bodyNotSetFlag; // used for threads
85  
86      public MgnlEmail(MailTemplate template) {
87          super(template.initSession());
88          this.template = template;
89      }
90  
91      public abstract void setBody(String text) throws Exception;
92  
93      @Override
94      public void setSubject(String arg0) throws MessagingException {
95          this.setSubject(arg0, "UTF-8");
96      }
97  
98      public boolean isBodyNotSetFlag() {
99          return this.bodyNotSetFlag;
100     }
101 
102     public void setBodyNotSetFlag(boolean _bodyNotSetFlag) {
103         this.bodyNotSetFlag = _bodyNotSetFlag;
104     }
105 
106     public void setTemplate(MailTemplate template) {
107         this.template = template;
108         try {
109             setHeader(CONTENT_TYPE, getContentType());
110         } catch (MessagingException e) {
111             log.error("Couldn't set content type");
112         }
113     }
114 
115     public MailTemplate getTemplate() {
116         return this.template;
117     }
118 
119     /**
120      * @noinspection MethodOverloadsMethodOfSuperclass
121      */
122     public void setFrom(String _from) {
123         try {
124             InternetAddress address;
125             Matcher matcher = MgnlEmail.EMAIL_WITH_PERSONAL_PATTERN.matcher(_from);
126             if (matcher.matches()) {
127                 String email = matcher.group(2);
128                 String personal = matcher.group(1);
129                 address = new InternetAddress(email, personal, "UTF8");
130             } else {
131                 address = new InternetAddress(_from);
132             }
133             this.setFrom(address);
134         }
135         catch (Exception e) {
136             log.error("Could not set from field of email:" + e.getMessage());
137         }
138     }
139 
140     public void setCharsetHeader(String charset) throws MailException {
141         try {
142             StringBuffer contentType = new StringBuffer(this.getHeader(CONTENT_TYPE, TEXT_PLAIN_UTF));
143             int index = contentType.lastIndexOf(";");
144             if (index != -1) {
145                 contentType.substring(0, index);
146             }
147             contentType.append(CHARSET_HEADER_STRING).append(charset);
148         }
149         catch (Exception e) {
150             throw new MailException("Content type is not set. Set the content type before setting the charset");
151         }
152     }
153 
154     public void setToList(String list) throws Exception {
155         setRecipients(Message.RecipientType.TO, createAdressList(MailUtil.convertEmailList(list)));
156     }
157 
158     public void setCcList(String list) throws Exception {
159         setRecipients(Message.RecipientType.CC, createAdressList(list));
160     }
161 
162     public void setBccList(String list) throws Exception {
163         setRecipients(Message.RecipientType.BCC, createAdressList(list));
164     }
165 
166     public void setReplyToList(String list) throws Exception {
167         setReplyTo(createAdressList(list));
168     }
169 
170     private Address[] createAdressList(String adresses) throws AddressException {
171         if (adresses == null || adresses.equals(StringUtils.EMPTY)) {
172             return new Address[0];
173         }
174         String[] addressesArr = adresses.split("\n");
175         List<InternetAddress> atos = new ArrayList<InternetAddress>();
176         for (String address : addressesArr) {
177             try {
178                 atos.add(new InternetAddress(address));
179             } catch (AddressException e) {
180                 log.warn("Error while parsing address.", e);
181             }
182         }
183         return atos.toArray(new Address[atos.size()]);
184     }
185 
186     public void setAttachments(List<MailAttachment> list) throws MailException {
187         if (list == null) {
188             return;
189         }
190         if (log.isDebugEnabled()) {
191             log.debug("Set attachments [" + list.size() + "] for mail: [" + this.getClass().getName() + "]");
192         }
193         for (MailAttachment attachment : list) {
194             addAttachment(attachment);
195         }
196     }
197 
198     public MimeBodyPart addAttachment(MailAttachment attachment) throws MailException {
199         throw new MailException("Cannot add attachment to this email. It is not a Multimime email");
200     }
201 
202     public void setBodyFromResourceFile() throws Exception {
203 
204         URL url = this.getClass().getResource("/" + template.getTemplateFile());
205         log.info("This is the url:" + url);
206         BufferedReader br = new BufferedReader(new FileReader(url.getFile()));
207         String line;
208         StringBuffer buffer = new StringBuffer();
209         try {
210             while ((line = br.readLine()) != null) {
211                 buffer.append(line).append(File.separator);
212             }
213         } finally {
214             IOUtils.closeQuietly(br);
215         }
216 
217         this.setBody(buffer.toString());
218     }
219 
220     @Override
221     public String getContentType() {
222         if (template == null || StringUtils.isEmpty(template.getContentType())
223                 || StringUtils.equalsIgnoreCase(template.getContentType(), "HTML")) {
224             return TEXT_HTML_UTF;
225         } else {
226             return TEXT_PLAIN_UTF;
227         }
228     }
229 
230     public void setBody() throws Exception {
231         if(this.getTemplate() != null && this.getTemplate().getText() != null) {
232             setBody(this.getTemplate().getText());
233         } else if(this.getContent() == null) {
234             throw new Exception("no message set");
235         }
236     }
237 
238 }