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