001    /**
002     * Copyright 2005-2013 The Kuali Foundation
003     *
004     * Licensed under the Educational Community License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.opensource.org/licenses/ecl2.php
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package org.kuali.rice.core.mail;
017    
018    import org.kuali.rice.core.api.mail.EmailBcList;
019    import org.kuali.rice.core.api.mail.EmailBody;
020    import org.kuali.rice.core.api.mail.EmailCcList;
021    import org.kuali.rice.core.api.mail.EmailFrom;
022    import org.kuali.rice.core.api.mail.EmailSubject;
023    import org.kuali.rice.core.api.mail.EmailTo;
024    import org.kuali.rice.core.api.mail.EmailToList;
025    import org.kuali.rice.core.api.mail.MailMessage;
026    import org.kuali.rice.core.api.mail.Mailer;
027    import org.springframework.mail.MailException;
028    import org.springframework.mail.SimpleMailMessage;
029    import org.springframework.mail.javamail.JavaMailSenderImpl;
030    
031    import javax.activation.DataHandler;
032    import javax.mail.Address;
033    import javax.mail.Message;
034    import javax.mail.MessagingException;
035    import javax.mail.internet.AddressException;
036    import javax.mail.internet.InternetAddress;
037    import javax.mail.internet.MimeMessage;
038    import javax.mail.util.ByteArrayDataSource;
039    import java.io.IOException;
040    
041    
042    /**
043     * Maintains a Java Mail session and is used for sending e-mails.
044     *
045     * @author Kuali Rice Team (rice.collab@kuali.org)
046     */
047    public class MailerImpl implements Mailer {
048    
049                protected final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(MailerImpl.class);
050    
051                private JavaMailSenderImpl mailSender;        
052                
053                    /**
054                     * @param mailSender The injected Mail Sender.
055                     */
056                    public void setMailSender(JavaMailSenderImpl mailSender) {
057                            this.mailSender = mailSender;
058                    }
059                
060                    /**
061                 * Construct and a send simple email message from a Mail Message.
062                 * 
063                 * @param message
064                 *            the Mail Message
065                     * @throws MessagingException 
066                 */
067                    @Override
068            @SuppressWarnings("unchecked")
069                    public void sendEmail(MailMessage message) throws MessagingException {
070                    
071                    // Construct a simple mail message from the Mail Message
072                    SimpleMailMessage smm = new SimpleMailMessage();
073                    smm.setTo( (String[])message.getToAddresses().toArray(new String[message.getToAddresses().size()]) );
074                    smm.setBcc( (String[])message.getBccAddresses().toArray(new String[message.getBccAddresses().size()]) );
075                    smm.setCc( (String[])message.getCcAddresses().toArray(new String[message.getCcAddresses().size()]) );
076                    smm.setSubject(message.getSubject());
077                    smm.setText(message.getMessage());
078                    smm.setFrom(message.getFromAddress());
079    
080                    try {
081                            if ( LOG.isDebugEnabled() ) {
082                                    LOG.debug( "sendEmail() - Sending message: " + smm.toString() );
083                            }
084                        mailSender.send(smm);
085                    }
086                    catch (Exception e) {
087                            LOG.error("sendEmail() - Error sending email.", e);
088                                    throw new RuntimeException(e);
089                    }
090                }
091                    
092                    /**
093                 * Send an email to a single recipient with the specified subject and message. This is a convenience 
094                 * method for simple message addressing.
095                 * 
096                 * @param from
097                 *            sender of the message            
098                 * @param to
099                 *            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    }