View Javadoc

1   /**
2    * This file Copyright (c) 2003-2010 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   * Date: Mar 30, 2006 Time: 1:01:37 PM
65   * @author <a href="mailto:niko@macnica.com">Nicolas Modrzyk</a>
66   */
67  public abstract class MgnlEmail extends MimeMessage {
68  
69      protected static final String CONTENT_TYPE = "Content-Type";
70  
71      protected static final String TEXT_PLAIN_UTF = "text/plain; charset=UTF-8";
72  
73      protected static final String TEXT_HTML_UTF = "text/html; charset=UTF-8";
74  
75      protected static final String CHARSET_HEADER_STRING = "charset=";
76  
77      protected static final Pattern EMAIL_WITH_PERSONAL_PATTERN = Pattern.compile("\"+(.*)\"+<(.*)>");
78  
79      public static Logger log = LoggerFactory.getLogger(MgnlEmail.class);
80  
81      private MailTemplate template;
82  
83      private boolean bodyNotSetFlag; // used for threads
84  
85      public MgnlEmail(MailTemplate template) {
86          super(template.initSession());
87          this.template = template;
88      }
89  
90      public abstract void setBody(String text) throws Exception;
91  
92      public void setSubject(String arg0) throws MessagingException {
93          this.setSubject(arg0, "UTF-8");
94      }
95  
96      public boolean isBodyNotSetFlag() {
97          return this.bodyNotSetFlag;
98      }
99  
100     public void setBodyNotSetFlag(boolean _bodyNotSetFlag) {
101         this.bodyNotSetFlag = _bodyNotSetFlag;
102     }
103 
104     public void setTemplate(MailTemplate template) {
105         this.template = template;
106         try {
107             setHeader(CONTENT_TYPE, getContentType());
108         } catch (MessagingException e) {
109             log.error("Couldn't set content type");
110         }
111     }
112 
113     public MailTemplate getTemplate() {
114         return this.template;
115     }
116 
117     /**
118      * @noinspection MethodOverloadsMethodOfSuperclass
119      */
120     public void setFrom(String _from) {
121         try {
122             InternetAddress address;
123             Matcher matcher = MgnlEmail.EMAIL_WITH_PERSONAL_PATTERN.matcher(_from);
124             if (matcher.matches()) {
125                 String email = matcher.group(2);
126                 String personal = matcher.group(1);
127                 address = new InternetAddress(email, personal, "UTF8");
128             } else {
129                 address = new InternetAddress(_from);
130             }
131             this.setFrom(address);
132         }
133         catch (Exception e) {
134             log.error("Could not set from field of email:" + e.getMessage());
135         }
136     }
137 
138     public void setCharsetHeader(String charset) throws MailException {
139         try {
140             StringBuffer contentType = new StringBuffer(this.getHeader(CONTENT_TYPE, TEXT_PLAIN_UTF));
141             int index = contentType.lastIndexOf(";");
142             if (index != -1) {
143                 contentType.substring(0, index);
144             }
145             contentType.append(CHARSET_HEADER_STRING).append(charset);
146         }
147         catch (Exception e) {
148             throw new MailException("Content type is not set. Set the content type before setting the charset");
149         }
150     }
151 
152     public void setToList(String list) throws Exception {
153         setRecipients(Message.RecipientType.TO, createAdressList(MailUtil.convertEmailList(list)));
154     }
155 
156     public void setCcList(String list) throws Exception {
157         setRecipients(Message.RecipientType.CC, createAdressList(list));
158     }
159 
160     public void setBccList(String list) throws Exception {
161         setRecipients(Message.RecipientType.BCC, createAdressList(list));
162     }
163 
164     public void setReplyToList(String list) throws Exception {
165         setReplyTo(createAdressList(list));
166     }
167 
168     private Address[] createAdressList(String adresses) throws AddressException {
169         if (adresses == null || adresses.equals(StringUtils.EMPTY)) {
170             return new Address[0];
171         }
172         String[] addressesArr = adresses.split("\n");
173         List<InternetAddress> atos = new ArrayList<InternetAddress>();
174         for (String address : addressesArr) {
175             try {
176                 atos.add(new InternetAddress(address));
177             } catch (AddressException e) {
178                 log.warn("Error while parsing address.", e);
179             }
180         }
181         return atos.toArray(new Address[atos.size()]);
182     }
183 
184     public void setAttachments(List<MailAttachment> list) throws MailException {
185         if (list == null) {
186             return;
187         }
188         if (log.isDebugEnabled()) {
189             log.debug("Set attachments [" + list.size() + "] for mail: [" + this.getClass().getName() + "]");
190         }
191         for (MailAttachment attachment : list) {
192             addAttachment(attachment);
193         }
194     }
195 
196     public MimeBodyPart addAttachment(MailAttachment attachment) throws MailException {
197         throw new MailException("Cannot add attachment to this email. It is not a Multimime email");
198     }
199 
200     public void setBodyFromResourceFile() throws Exception {
201 
202         URL url = this.getClass().getResource("/" + template.getTemplateFile());
203         log.info("This is the url:" + url);
204         BufferedReader br = new BufferedReader(new FileReader(url.getFile()));
205         String line;
206         StringBuffer buffer = new StringBuffer();
207         try {
208             while ((line = br.readLine()) != null) {
209                 buffer.append(line).append(File.separator);
210             }
211         } finally {
212             IOUtils.closeQuietly(br);
213         }
214 
215         this.setBody(buffer.toString());
216     }
217 
218     public String getContentType() {
219         if (template == null || StringUtils.isEmpty(template.getContentType())
220                 || StringUtils.equalsIgnoreCase(template.getContentType(), "HTML")) {
221             return TEXT_HTML_UTF;
222         } else {
223             return TEXT_PLAIN_UTF;
224         }
225     }
226 
227     public void setBody() throws Exception {
228         if(this.getTemplate() != null && this.getTemplate().getText() != null) {
229             setBody(this.getTemplate().getText());
230         } else if(this.getContent() == null) {
231             throw new Exception("no message set");
232         }
233     }
234 
235 }