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  
39  import java.net.URL;
40  import java.util.List;
41  
42  import javax.activation.DataHandler;
43  import javax.activation.DataSource;
44  import javax.activation.FileDataSource;
45  import javax.activation.URLDataSource;
46  import javax.mail.BodyPart;
47  import javax.mail.internet.MimeBodyPart;
48  import javax.mail.internet.MimeMultipart;
49  
50  
51  /**
52   * A base class for sending mails with attachments.
53   * The class contains hierarchical structure of MimeMultipart and MimeBodyPart:
54   *  - MimeMultipart multipartMixed - multipart/mixed
55   *  -- MimeMultipart multipartRelated - multipart/related
56   *  --- MimeBodyPart messageBodyPart - text/plain, text/html - the text part of email
57   *  --- MimeBodyPart attachmentBodyPart - the attachments which are shown in text part of message
58   *  -- MimeBodyPart attachmentBodyPart - attachments connected only like attachments in mail clients
59   *
60   * Date: Apr 1, 2006 Time: 9:00:35 PM
61   * @author <a href="mailto:niko@macnica.com">Nicolas Modrzyk</a>
62   */
63  public abstract class MgnlMultipartEmail extends MgnlEmail {
64  
65      private static final String CONTENT_ID = "Content-ID";
66  
67      private static final String RELATED = "related";
68  
69      private static final String MIXED = "mixed";
70  
71      protected MimeMultipart multipartMixed;
72  
73      protected MimeMultipart multipartRelated;
74  
75      public boolean isMultipart() {
76          // if exist top level MimeMultipart of email hierarchy -> then the email is multipart
77          return (this.multipartMixed != null);
78      }
79  
80      public MimeMultipart getMailMultipart() {
81          // return top level MimeMultipart of email hierarchy
82          return this.multipartMixed;
83      }
84  
85      public MgnlMultipartEmail(MailTemplate template) {
86          super(template);
87      }
88  
89      @Override
90      public MimeBodyPart addAttachment(MailAttachment attachment) throws MailException {
91  
92          try {
93              if (!isMultipart()) {
94                  turnOnMultipart();
95              }
96              MimeBodyPart attachmentBodyPart = new MimeBodyPart();
97              String key = attachment.getName();
98              log.info("Found new attachment with name :" + key);
99  
100             // get info on the attachment
101             URL url = attachment.getUrl();
102             String name = attachment.getFileName();
103             String contentType = attachment.getContentType();
104 
105             // set the disposition of the file.
106             attachmentBodyPart.setDisposition(attachment.getDisposition() + "; filename=\"" + name + "\"");
107 
108             // Fetch the image and associate to part
109             DataSource fds = url.getProtocol().startsWith("file:")
110                 ? new FileDataSource(url.getFile())
111                 : new URLDataSource(url);
112             // DataSource fd = new FileDataSource(file);
113             attachmentBodyPart.setDataHandler(new DataHandler(fds));
114             // Add a header to connect to the HTML
115 
116             // MAGNOLIA-1649 this is really important!
117             if (!key.startsWith("<")) {
118                 key = "<" + key + ">";
119             }
120             attachmentBodyPart.setHeader(CONTENT_ID, key);
121 
122             // set the header as well as the content type do this AFTER setting the data source
123             attachmentBodyPart.setHeader(CONTENT_TYPE, contentType + "; name=\"" + name + "\"");
124 
125             // add attachment to appropriate part of email structure
126             if(attachment.getMimeMultipart().equals(RELATED)){
127                 this.multipartRelated.addBodyPart(attachmentBodyPart);
128             }else{
129                 this.multipartMixed.addBodyPart(attachmentBodyPart);
130             }
131 
132             return attachmentBodyPart;
133         }
134         catch (Exception e) {
135             throw new MailException(e.getMessage(), e);
136         }
137     }
138 
139     private void turnOnMultipart() {
140 
141         try {
142             if(this.multipartMixed == null) {
143                 this.multipartMixed = new MimeMultipart(MIXED);
144                 this.multipartRelated = new MimeMultipart(RELATED);
145                 MimeBodyPart relatedBodyPart = new MimeBodyPart();
146                 relatedBodyPart.setContent(multipartRelated);
147                 this.multipartMixed.addBodyPart(relatedBodyPart);
148             }
149             if(this.getContent() != null) {
150 
151                 Object o = this.getContent();
152                 if (o instanceof String) {
153                     BodyPart messageBodyPart = new MimeBodyPart();
154                     messageBodyPart.setContent(o, getContentType());
155                     this.multipartRelated.addBodyPart(messageBodyPart, 0);
156                 }
157             }
158             this.setContent(this.multipartMixed);
159         }
160         catch (Exception e) {
161             log.info(e.getMessage());
162         }
163     }
164 
165     @Override
166     public void setBody(String body) throws Exception {
167 
168         this.setContent(body, getContentType());
169 
170         // If we didn't do this then if we call setBody twice or more -> it leads to add attachments multiple times.
171         // Also in another calls. The template may not have attachments, then we don't need send mail like MultipartEmail
172         this.multipartMixed = null;
173         this.multipartRelated = null;
174 
175         // process the attachments
176         final List<MailAttachment> attachments = super.getTemplate().getAttachments();
177         if (attachments != null) {
178             setAttachments(attachments);
179         }
180     }
181 
182 }