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