View Javadoc

1   /*
2    * Copyright 2005-2007 The Kuali Foundation
3    * 
4    * 
5    * Licensed under the Educational Community License, Version 2.0 (the "License");
6    * you may not use this file except in compliance with the License.
7    * You may obtain a copy of the License at
8    * 
9    * http://www.opensource.org/licenses/ecl2.php
10   * 
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.kuali.rice.kew.mail;
18  
19  import java.util.Properties;
20  
21  import javax.activation.DataHandler;
22  import javax.mail.Address;
23  import javax.mail.Authenticator;
24  import javax.mail.Message;
25  import javax.mail.MessagingException;
26  import javax.mail.NoSuchProviderException;
27  import javax.mail.PasswordAuthentication;
28  import javax.mail.Session;
29  import javax.mail.Transport;
30  import javax.mail.internet.AddressException;
31  import javax.mail.internet.InternetAddress;
32  import javax.mail.internet.MimeMessage;
33  
34  import org.kuali.rice.kew.util.ByteArrayDataSource;
35  
36  
37  /**
38   * Maintains a Java Mail session and can be used for sending emails.
39   *
40   * @author Kuali Rice Team (rice.collab@kuali.org)
41   */
42  public class Mailer {
43  
44  	    protected final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(getClass());
45  
46  	    private Properties configProperties;
47  	    private Authenticator authenticator;
48  
49  	    private Session currentSession;
50  
51  	    /**
52  	     * Create a AuthenticatedMailer with the default values for authenticated
53  	     * use of mail-relay.iu.edu.
54  	     * 
55  	     * The Kerberos principle and and password should be a system principle
56  	     * rather than a user principle.
57  	     * 
58  	     * @param senderAddress
59  	     *            return address for the mail being sent
60  	     * @param kbPrincipleName
61  	     *            kerberos principle name used to authenticate to mail-relay
62  	     * @param kbPrinciplePassword
63  	     *            kerberos principle password used to authenticate to mail-relay
64  	     */
65  	    public Mailer(Properties configProperties, Authenticator authenticator) {
66  	    	this.configProperties = configProperties;
67  	    	this.authenticator = authenticator;
68  	    }
69  	    
70  	    public Mailer(Properties configProperties) {
71  	    	this(configProperties, null);
72  	    }
73  	    
74  	    public Mailer(Properties configProperties, String username, String password) {
75  	    	this(configProperties, new SimpleAuthenticator(username, password));
76  	    }
77  
78  	    /**
79  	     * A method to configure the Mailer properties. This class will default to a
80  	     * set of properties but this method allows the calling program to set the
81  	     * specific properties.
82  	     * 
83  	     * @param mailConfigProperties
84  	     *            Proeprties object containing configuration information
85  	     */
86  	    public void setConfig(Properties configProperties) {
87  	        this.configProperties = configProperties;
88  	    }
89  
90  	    /**
91  	     * Sends an email to the given recipients.
92  	     * 
93  	     * @param recipients
94  	     *            list of addresses to which the message is sent
95  	     * @param subject
96  	     *            subject of the message
97  	     * @param messageBody
98  	     *            body of the message
99  	     * @param ccRecipients
100 	     *            list of addresses which are to be cc'd on the message
101 	     * @param bccRecipients
102 	     *            list of addresses which are to be bcc'd on the message
103 	     *
104 	     * @throws AddressException
105 	     * @throws MessagingException
106 	     */
107 	    public void sendMessage(String sender, Address[] recipients, String subject, String messageBody, Address[] ccRecipients, Address[] bccRecipients, boolean htmlMessage) throws AddressException, MessagingException {
108 	    	Session session = getCurrentSession();
109 	    	session.setDebug(LOG.isDebugEnabled());
110 	        Message message = new MimeMessage(session);
111 
112 	        // From Address
113 	        message.setFrom(new InternetAddress(sender));
114 
115 	        // To Address
116 	        if (recipients != null && recipients.length > 0) {
117 	            message.addRecipients(Message.RecipientType.TO, recipients);
118 	        } else {
119 	            LOG.warn("No recipients indicated");
120 	        }
121 
122 	        // CC Address
123 	        if (ccRecipients != null && ccRecipients.length > 0) {
124 	            message.addRecipients(Message.RecipientType.CC, ccRecipients);
125 	        }
126 
127 	        // BCC Address
128 	        if (bccRecipients != null && bccRecipients.length > 0) {
129 	            message.addRecipients(Message.RecipientType.BCC, bccRecipients);
130 	        }
131 
132 	        // The Subject
133 	        message.setSubject(subject);
134 	        if (subject == null || "".equals(subject)) {
135 	            LOG.warn("Empty subject being sent");
136 	        }
137 
138 	        // Now the message body.
139 
140 	        if (htmlMessage) {
141 	            prepareHtmlMessage(messageBody, message);
142 	        } else {
143 	            message.setText(messageBody);
144 	            if (messageBody == null || "".equals(messageBody)) {
145 	                LOG.warn("Empty message body being sent.");
146 	            }
147 	        }
148 
149 	        // Finally, send the message!
150 	        Transport.send(message);
151 
152 	    }
153 
154 	    /**
155 	     * Send a message to the designated recipient with the specified subject and
156 	     * message. This is a convience class for simple message addressing
157 	     * 
158 	     * @param recipient
159 	     *            the email address to which the message is sent
160 	     * @param subject
161 	     *            subject for the message
162 	     * @param messageBody
163 	     *            body of the message to to be sent
164 	     * @param ccRecipient
165 	     *            email address of a cc recipient
166 	     */
167 	    public void sendMessage(String sender, String recipient, String subject, String messageBody, boolean htmlMessage) throws AddressException, MessagingException {
168 	        final Address[] NO_RECIPIENTS = null;
169 	        Address[] recipients = { new InternetAddress(recipient) };
170 	        sendMessage(sender, recipients, subject, messageBody, NO_RECIPIENTS, NO_RECIPIENTS, htmlMessage);
171 	    }
172 
173 	    /**
174 	     * @return current properties used to configure the mail session
175 	     */
176 	    public Properties getConfig() {
177 	        return configProperties;
178 	    }
179 	    
180 	    public Authenticator getAuthenticator() {
181 	    	return authenticator;
182 	    }
183 
184 	    /**
185 	     * This allows direct access to the Mail Session. While this offers more
186 	     * flexibility, the AuthenticatedMailer will no longer be responsible for
187 	     * management of the this session.
188 	     * 
189 	     * @return get the current session. If current session is null it creates a
190 	     *         new one.
191 	     */
192 	    public Session getCurrentSession() throws NoSuchProviderException {
193 	        if (this.currentSession == null || !this.currentSession.getTransport().isConnected()) {
194 	            this.currentSession = Session.getInstance(configProperties, authenticator);
195 	        }
196 	        return currentSession;
197 	    }
198 
199 	    private void prepareHtmlMessage(String messageText, Message message) throws MessagingException {
200 	        message.setDataHandler(new DataHandler(new ByteArrayDataSource(messageText, "text/html")));
201 	    }
202 	    
203 	    /**
204 	     * SimpleAuthenticator is used to do simple authentication when the SMTP
205 	     * server requires it.
206 	     */
207 	    private static class SimpleAuthenticator extends javax.mail.Authenticator {
208 	    	
209 	    	private final PasswordAuthentication passwordAuthentication;
210 
211 	        private SimpleAuthenticator(String username, String password) {
212 	        	this.passwordAuthentication = new PasswordAuthentication(username, password);
213 	        }
214 
215 	        public PasswordAuthentication getPasswordAuthentication() {
216 	            return passwordAuthentication;
217 	        }
218 	        
219 	    }
220 	
221 }