View Javadoc
1   /*
2    * $Source$
3    * $Revision$
4    *
5    * Copyright (C) 2006 Tim Pizey
6    *
7    * Part of Melati (http://melati.org), a framework for the rapid
8    * development of clean, maintainable web applications.
9    *
10   * Melati is free software; Permission is granted to copy, distribute
11   * and/or modify this software under the terms either:
12   *
13   * a) the GNU General Public License as published by the Free Software
14   *    Foundation; either version 2 of the License, or (at your option)
15   *    any later version,
16   *
17   *    or
18   *
19   * b) any version of the Melati Software License, as published
20   *    at http://melati.org
21   *
22   * You should have received a copy of the GNU General Public License and
23   * the Melati Software License along with this program;
24   * if not, write to the Free Software Foundation, Inc.,
25   * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA to obtain the
26   * GNU General Public License and visit http://melati.org to obtain the
27   * Melati Software License.
28   *
29   * Feel free to contact the Developers of Melati (http://melati.org),
30   * if you would like to work out a different arrangement than the options
31   * outlined here.  It is our intention to allow Melati to be used by as
32   * wide an audience as possible.
33   *
34   * This program is distributed in the hope that it will be useful,
35   * but WITHOUT ANY WARRANTY; without even the implied warranty of
36   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37   * GNU General Public License for more details.
38   *
39   * Contact details for copyright holder:
40   *
41   *     Tim Pizey <timp At paneris.org>
42   *     http://paneris.org/~timp
43   */
44  package org.melati.util;
45  
46  import java.io.File;
47  import java.io.IOException;
48  
49  import javax.activation.DataHandler;
50  import javax.activation.FileDataSource;
51  import javax.mail.Address;
52  import javax.mail.Message;
53  import javax.mail.MessagingException;
54  import javax.mail.Multipart;
55  import javax.mail.Session;
56  import javax.mail.Transport;
57  import javax.mail.internet.InternetAddress;
58  import javax.mail.internet.MimeBodyPart;
59  import javax.mail.internet.MimeMessage;
60  import javax.mail.internet.MimeMultipart;
61  
62  /**
63   * Send an email to one or more recipients with or without attachments.
64   */
65  public final class Email {
66  
67    private Email() {
68    }
69  
70    /**
71     * Send the email.
72     * @param smtpServer name of SMTP server to use
73     * @param from email address and optionally name of sender
74     * @param to email address and optionally name of recipient 
75     * @param replyto email address and optionally name to reply to
76     * @param subject subject of message
77     * @param text text body of email
78     */
79    public static void send(String smtpServer, String from, String to,
80                            String replyto, String subject, String text) 
81        throws EmailException, IOException {
82      File[] empty = {};
83      sendWithAttachments(smtpServer, from, to, replyto, subject, text, empty);
84    }
85  
86    /**
87     * Send the email to a list of recipients.
88     * 
89     * @param smtpServer name of SMTP server to use
90     * @param from email address and optionally name of sender
91     * @param toList list of email addresses and optionally names of recipients
92     * @param replyto email address and optionally name to reply to
93     * @param subject subject of message
94     * @param message text body of email
95     */
96    public static void sendToList(String smtpServer, String from,
97            String[] toList,  String replyto, String subject,
98            String message) throws EmailException, IOException {
99      File[] empty = {};
100 
101     for (int i = 0; i < toList.length; i++)
102       sendWithAttachments(smtpServer, from, toList[i], replyto, subject, message, empty);
103   }
104   
105   /**
106    * Send message with attachments.
107    * 
108    * @param smtpServer name of SMTP server to use
109    * @param from email address and optionally name of sender
110    * @param to email address and optionally name of recipient 
111    * @param replyto email address and optionally name to reply to
112    * @param subject subject of message
113    * @param text text body of email
114    * @param attachments Array of files to attach
115    */
116   public static void sendWithAttachments(String smtpServer, String from,
117           String to, String replyto, String subject, String text, File[] attachments)
118           throws EmailException, IOException {
119 
120     // Construct the message
121     Message message = initialiseMessage(smtpServer, from, to, replyto, subject);
122     try {
123       // create and fill the first, text message part
124       MimeBodyPart mbp1 = new MimeBodyPart();
125       mbp1.setText(text);
126       Multipart mp = new MimeMultipart();
127       mp.addBodyPart(mbp1);
128       for (int i = 0; i < attachments.length; i++) {
129         File f = attachments[i];
130         if (f != null) {
131           // create the second message part
132           MimeBodyPart mbp2 = new MimeBodyPart();
133           // attach the file to the message
134           FileDataSource fds = new FileDataSource(f);
135           mbp2.setDataHandler(new DataHandler(fds));
136           mbp2.setFileName(fds.getName());
137           mp.addBodyPart(mbp2);
138         }
139       }
140       // add the Multipart to the message
141       message.setContent(mp);
142     } catch (Exception e) {
143       e.printStackTrace();
144       throw new EmailException("Problem creating message: " + e.toString());
145     }
146     // send the message
147     post(message);
148   }
149   
150   /**
151    * Send HTML message with attachments.
152    * 
153    * @param smtpServer name of SMTP server to use
154    * @param from email address and optionally name of sender
155    * @param to email address and optionally name of recipient 
156    * @param replyto email address and optionally name to reply to
157    * @param subject subject of message
158    * @param plainText text body of email
159    * @param htmlText HTML body of email
160    * @param referenced Array of Files referenced withing the HTML body
161    * @param attachments Array of files to attach
162    */
163   public static void sendAsHtmlWithAttachments(String smtpServer, String from,
164           String to, String replyto, String subject, String plainText,
165           String htmlText, File[] referenced, File[] attachments)
166           throws EmailException, IOException {
167 
168     // Construct the message
169     Message message = initialiseMessage(smtpServer, from, to, replyto, subject);
170     try {
171       Multipart mp = new MimeMultipart("related");
172       MimeBodyPart mbp1 = new MimeBodyPart();
173       //mbp1.setText(plainText);
174       mbp1.setContent(plainText, "text/plain");
175       mp.addBodyPart(mbp1);
176       MimeBodyPart mbp2 = new MimeBodyPart();
177       mbp2.setContent(htmlText, "text/html");
178       mp.addBodyPart(mbp2);
179 
180       if (referenced != null) {
181         for (int i = 0; i < referenced.length; i++) {
182           File f = referenced[i];
183           if (f != null) {
184             MimeBodyPart mbp3 = new MimeBodyPart();
185             FileDataSource fds = new FileDataSource(f);
186             mbp3.setDataHandler(new DataHandler(fds));
187             mbp3.setFileName(fds.getName());
188             mp.addBodyPart(mbp3);
189           }
190         }
191       }
192       if (attachments != null) {
193         for (int i = 0; i < attachments.length; i++) {
194           File f = attachments[i];
195           if (f != null) {
196             MimeBodyPart mbp4 = new MimeBodyPart();
197             if (f.getName() == null) {
198               System.out.println("name is null");
199             }
200             FileDataSource fds = new FileDataSource(f);
201             mbp4.setDataHandler(new DataHandler(fds));
202             mbp4.setFileName(fds.getName());
203             mp.addBodyPart(mbp4);
204           }
205         }
206       }
207       // add the Multipart to the message
208       message.setContent(mp);
209     } catch (Exception e) {
210       e.printStackTrace();
211       throw new EmailException("Problem creating message: " + e.toString());
212     }
213     // send the message
214     post(message);
215   }
216 
217   private static Message initialiseMessage(String smtpServer, String from,
218           String to, String replyto, String subject) throws EmailException {
219     // Create the JavaMail session
220     // The properties for the whole system, sufficient to send a mail
221     // and much more besides.
222     java.util.Properties properties = System.getProperties();
223     properties.put("mail.smtp.host", smtpServer);
224     // this is required if InetAddress.getLocalHost().getHostName()  returns null
225     // which it does nor me in Eclipse
226     properties.put("mail.smtp.localhost", smtpServer);
227     Session session = Session.getInstance(properties, null);
228     MimeMessage message = new MimeMessage(session);
229     // Set the from address
230     Address fromAddress;
231     try {
232       fromAddress = new InternetAddress(from);
233       message.setFrom(fromAddress);
234       // Parse and set the recipient addresses
235       Address[] toAddresses = InternetAddress.parse(to);
236       message.setRecipients(Message.RecipientType.TO, toAddresses);
237       /*
238        * Address[] ccAddresses = InternetAddress.parse(cc);
239        * message.setRecipients(Message.RecipientType.CC,ccAddresses);
240        * 
241        * Address[] bccAddresses = InternetAddress.parse(bcc);
242        * message.setRecipients(Message.RecipientType.BCC,bccAddresses);
243        */
244       if (replyto != null) {
245         Address[] replyTos = InternetAddress.parse(replyto);
246         message.setReplyTo(replyTos);
247       }
248       message.setSubject(subject);
249     } catch (Exception e) {
250       e.printStackTrace();
251       throw new EmailException("Problem sending message: " + e.toString());
252     }
253     return message;
254   }
255   
256   private static void post(Message message) throws EmailException {
257     try {
258       Transport.send(message);
259     } catch (MessagingException e) {
260       e.printStackTrace();
261       throw new EmailException("Problem sending message: " + e.toString());
262     }
263     
264   }
265   /**
266    * @return a fancy email address
267    */
268   public static String mailAddress(String name, String email) {
269     return name + " <" + email + ">";
270   }
271 
272 }