View Javadoc

1   /**
2    * Copyright 2005-2011 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.core.mail;
17  
18  import org.springframework.mail.MailException;
19  import org.springframework.mail.SimpleMailMessage;
20  import org.springframework.mail.javamail.JavaMailSenderImpl;
21  
22  import javax.activation.DataHandler;
23  import javax.mail.Address;
24  import javax.mail.Message;
25  import javax.mail.MessagingException;
26  import javax.mail.internet.AddressException;
27  import javax.mail.internet.InternetAddress;
28  import javax.mail.internet.MimeMessage;
29  import javax.mail.util.ByteArrayDataSource;
30  import java.io.IOException;
31  
32  
33  /**
34   * Maintains a Java Mail session and is used for sending e-mails.
35   *
36   * @author Kuali Rice Team (rice.collab@kuali.org)
37   */
38  public class Mailer {
39  
40  	    protected final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(Mailer.class);
41  
42  	    private JavaMailSenderImpl mailSender;	  
43  	    
44  		/**
45  		 * @param mailSender The injected Mail Sender.
46  		 */
47  		public void setMailSender(JavaMailSenderImpl mailSender) {
48  			this.mailSender = mailSender;
49  		}
50  	    
51  		/**
52  	     * Construct and a send simple email message from a Mail Message.
53  	     * 
54  	     * @param message
55  	     *            the Mail Message
56  		 * @throws MessagingException 
57  	     */
58  		@SuppressWarnings("unchecked")
59  		public void sendEmail(MailMessage message) throws MessagingException {
60  	        
61  	        // Construct a simple mail message from the Mail Message
62  	        SimpleMailMessage smm = new SimpleMailMessage();
63  	        smm.setTo( (String[])message.getToAddresses().toArray(new String[message.getToAddresses().size()]) );
64  	        smm.setBcc( (String[])message.getBccAddresses().toArray(new String[message.getBccAddresses().size()]) );
65  	        smm.setCc( (String[])message.getCcAddresses().toArray(new String[message.getCcAddresses().size()]) );
66  	        smm.setSubject(message.getSubject());
67  	        smm.setText(message.getMessage());
68  	        smm.setFrom(message.getFromAddress());
69  
70  	        try {
71  	        	if ( LOG.isDebugEnabled() ) {
72  	        		LOG.debug( "sendEmail() - Sending message: " + smm.toString() );
73  	        	}
74  	            mailSender.send(smm);
75  	        }
76  	        catch (Exception e) {
77  	        	LOG.error("sendEmail() - Error sending email.", e);
78  				throw new RuntimeException(e);
79  	        }
80  	    }
81  		
82  		/**
83  	     * Send an email to a single recipient with the specified subject and message. This is a convenience 
84  	     * method for simple message addressing.
85  	     * 
86  	     * @param from
87  	     *            sender of the message            
88  	     * @param to
89  	     *            list of addresses to which the message is sent
90  	     * @param subject
91  	     *            subject of the message
92  	     * @param body
93  	     *            body of the message
94  	     */
95  		public void sendEmail(EmailFrom from, EmailTo to, EmailSubject subject, EmailBody body, boolean htmlMessage) {
96  	        if (to.getToAddress() == null) {
97  	            LOG.warn("No To address specified. Refraining from sending mail.");
98  	            return;
99  	        }
100 			try {
101 		        Address[] singleRecipient = {new InternetAddress(to.getToAddress())};
102 				sendMessage(from.getFromAddress(),
103 						    singleRecipient,
104 						    subject.getSubject(),
105 						    body.getBody(), 
106 						    null,
107 						    null,
108 						    htmlMessage);
109 			} catch (Exception e) {
110 				LOG.error("sendEmail(): ", e);
111 				throw new RuntimeException(e);
112 			}
113 		}
114 
115 		/**
116 	     * Send an email to the given "to", "cc", and "bcc" recipients with the specified subject and message.
117 	     * 
118 	     * @param from
119 	     *            sender of the message            
120 	     * @param to
121 	     *            list of addresses to which the message is sent
122 	     * @param subject
123 	     *            subject of the message
124 	     * @param body
125 	     *            body of the message
126 	     * @param cc
127 	     *            list of addresses which are to be cc'd on the message
128 	     * @param bc
129 	     *            list of addresses which are to be bcc'd on the message
130 	     */
131 		public void sendEmail(EmailFrom from, EmailToList to, EmailSubject subject, EmailBody body, EmailCcList cc, EmailBcList bc, boolean htmlMessage) {
132 		    if (to.getToAddresses().isEmpty()) {
133 				LOG.error("List of To addresses must contain at least one entry. Refraining from sending mail.");
134 				return;
135 		    }
136 			try {
137 			    sendMessage(from.getFromAddress(), 
138 				            to.getToAddressesAsAddressArray(), 
139 				            subject.getSubject(), 
140 				            body.getBody(), 
141 							(cc == null ? null : cc.getToAddressesAsAddressArray()), 
142 							(bc == null ? null : bc.getToAddressesAsAddressArray()), 
143 							htmlMessage);
144 			} catch (Exception e) {
145 				LOG.error("sendEmail(): ", e);
146 				throw new RuntimeException(e);
147             }
148 		}
149 		
150 		/**
151 	     * Send an email to the given recipients with the specified subject and message.
152 	     * 
153 	     * @param from
154 	     *            sender of the message            
155 	     * @param to
156 	     *            list of addresses to which the message is sent
157 	     * @param subject
158 	     *            subject of the message
159 	     * @param messageBody
160 	     *            body of the message
161 	     * @param cc
162 	     *            list of addresses which are to be cc'd on the message
163 	     * @param bcc
164 	     *            list of addresses which are to be bcc'd on the message
165 	     */
166 	    protected void sendMessage(String from, Address[] to, String subject, String messageBody, Address[] cc, Address[] bcc, boolean htmlMessage) throws AddressException, MessagingException, MailException {
167 		    MimeMessage message = mailSender.createMimeMessage();
168 
169 	        // From Address
170 	        message.setFrom(new InternetAddress(from));
171 
172 	        // To Address(es)
173 	        if (to != null && to.length > 0) {
174 	            message.addRecipients(Message.RecipientType.TO, to);
175 	        } else {
176 	            LOG.error("No recipients indicated.");
177 	        }
178 
179 	        // CC Address(es)
180 	        if (cc != null && cc.length > 0) {
181 	            message.addRecipients(Message.RecipientType.CC, cc);
182 	        }
183 
184 	        // BCC Address(es)
185 	        if (bcc != null && bcc.length > 0) {
186 	            message.addRecipients(Message.RecipientType.BCC, bcc);
187 	        }
188 
189 	        // Subject
190 	        message.setSubject(subject);
191 	        if (subject == null || "".equals(subject)) {
192 	            LOG.warn("Empty subject being sent.");
193 	        }
194 
195 	        // Message body.
196 	        if (htmlMessage) {
197 	            prepareHtmlMessage(messageBody, message);
198 	        } else {
199 	            message.setText(messageBody);
200 	            if (messageBody == null || "".equals(messageBody)) {
201 	                LOG.warn("Empty message body being sent.");
202 	            }
203 	        }
204 
205 	        // Send the message
206 	        try {
207 	        	mailSender.send(message);
208 	        }
209 	        catch (Exception e) {
210 	        	LOG.error("sendMessage(): ", e);
211 	        	throw new RuntimeException(e);
212 	        }
213 	    }
214 
215 	    protected void prepareHtmlMessage(String messageText, Message message) throws MessagingException {
216 	        try {
217 				message.setDataHandler(new DataHandler(new ByteArrayDataSource(messageText, "text/html")));
218 			} catch (IOException e) {
219 				LOG.warn(e.getMessage());
220 				throw new RuntimeException(e);
221 			}
222 	    }
223 }