View Javadoc

1   /*
2    * The contents of this file are subject to the terms 
3    * of the Common Development and Distribution License 
4    * (the "License").  You may not use this file except 
5    * in compliance with the License.
6    * 
7    * You can obtain a copy of the license at 
8    * http://www.sun.com/cddl/cddl.html. 
9    * See the License for the specific language governing 
10   * permissions and limitations under the License.
11   * 
12   * When distributing Covered Code, include this CDDL 
13   * HEADER in each file and include the License file at 
14   * license.txt.  If applicable, add the following below 
15   * this CDDL HEADER, with the fields enclosed by brackets 
16   * "[]" replaced with your own identifying information: 
17   * Portions Copyright [yyyy] [name of copyright owner]
18   * 
19   * Portions Copyright 2004 eBay, Inc.
20   */
21  package com.ebay.carad.os.vitalsigns.util;
22  
23  import java.util.Properties;
24  
25  import javax.mail.Address;
26  import javax.mail.Message;
27  import javax.mail.MessagingException;
28  import javax.mail.Session;
29  import javax.mail.Transport;
30  import javax.mail.internet.InternetAddress;
31  import javax.mail.internet.MimeMessage;
32  
33  /***
34   * Simple util for sending a message.
35   * 
36   * @author Jeremy Kraybill
37   * @version $Id$
38   */
39  public abstract class MailUtil {
40  
41      /***
42  	 * Sends an e-mail message.
43  	 * 
44  	 * @param from an array of from e-mail addresses
45  	 * @param to an array of to e-mail addresses
46  	 * @param subject email subject
47  	 * @param body email body
48  	 * @param server SMTP server
49  	 * @throws MessagingException if bad things happen
50  	 */
51  	public static void sendMessage(String[] from, String[] to, String subject, String body, String server) throws MessagingException {
52  		Properties props = new Properties();
53  		Session session = Session.getDefaultInstance(props, null);
54  		MimeMessage message = new MimeMessage(session);
55  		message.setSubject(subject);
56  		message.setText(body);
57  		
58  		int fromCount = (from == null) ? 0 : from.length;
59  		Address[] fromAddresses = new InternetAddress[fromCount];
60  		for (int i = 0; i < fromCount; i++) {
61  			fromAddresses[i] = new InternetAddress(from[i]);
62  		}
63  		message.addFrom(fromAddresses);
64  		
65  		int toCount = (to == null) ? 0 : to.length;
66  		for (int i = 0; i < toCount; i++) {
67  			message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
68  		}
69  
70  		message.saveChanges(); // implicit with send()
71  		Transport transport = session.getTransport("smtp");
72  		transport.connect(server, null, null);
73  		transport.sendMessage(message, message.getAllRecipients());
74  		transport.close();
75  	}
76  
77  }