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