EmailService.java 18.4 KB
Newer Older
1
/**
2
 * Copyright (C) 2003-2008 Jive Software. All rights reserved.
3
 *
4 5 6 7 8 9 10 11 12 13 14
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
15 16 17 18 19 20
 */

package org.jivesoftware.util;

import java.security.Security;
import java.text.SimpleDateFormat;
21 22 23 24
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Properties;
25 26

import javax.mail.Address;
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
43 44 45 46 47 48 49 50

/**
 * A service to send email.<p>
 *
 * This class has a few factory methods you can use to return message objects
 * or to add messages into a queue to be sent. Using these methods, you can
 * send emails in the following couple of ways:<p>
 * <pre>
Matt Tucker's avatar
Matt Tucker committed
51
 *   EmailService.sendMessage(
52 53 54
 *     "Joe Bloe", "jbloe@place.org",
 *     "Jane Doe", "jane@doe.com",
 *     "Hello...",
Matt Tucker's avatar
Matt Tucker committed
55 56
 *     "This is the body of the email...",
 *     null
57 58 59 60
 *   );
 * </pre>
 * or
 * <pre>
Matt Tucker's avatar
Matt Tucker committed
61
 *   Message message = EmailService.createMimeMessage();
62 63 64 65
 *   // call setters on the message object
 *   // .
 *   // .
 *   // .
Matt Tucker's avatar
Matt Tucker committed
66
 *   emailService.sendMessage(message);
67 68 69 70
 * </pre><p>
 *
 * This class is configured with a set of Jive properties:<ul>
 *      <li><tt>mail.smtp.host</tt> -- the host name of your mail server, i.e.
Matt Tucker's avatar
Matt Tucker committed
71
 *          mail.yourhost.com. The default value is "localhost".
72 73 74 75 76 77 78 79
 *      <li><tt>mail.smtp.port</tt> -- an optional property to change the smtp
 *          port used from the default of 25.
 *      <li><tt>mail.smtp.username</tt> -- an optional property to change the
 *          username used to connect to the smtp server. Default is no username.
 *      <li><tt>mail.smtp.password</tt> -- an optional property to change the
 *          password used to connect to the smtp server. Default is no password.
 *      <li><tt>mail.smtp.ssl</tt> -- an optional property to set whether to use
 *          SSL to connect to the smtp server or not. Default is false.
Matt Tucker's avatar
Matt Tucker committed
80 81
 *      <li><tt>mail.debugEnabled</tt> -- true if debug information should written out.
 *          Default is false.
82 83 84 85
 * </ul>
 */
public class EmailService {

86 87
	private static final Logger Log = LoggerFactory.getLogger(EmailService.class);

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    private static final String SSL_FACTORY = "org.jivesoftware.util.SimpleSSLSocketFactory";

    private static EmailService instance = new EmailService();

    public static EmailService getInstance() {
        return instance;
    }

    private String host;
    private int port;
    private String username;
    private String password;
    private boolean sslEnabled;
    private boolean debugEnabled;

    private Session session = null;

    /**
     * Constructs a new EmailService instance.
     */
    private EmailService() {
Matt Tucker's avatar
Matt Tucker committed
109
        host = JiveGlobals.getProperty("mail.smtp.host", "localhost");
110 111 112 113 114 115 116 117 118 119 120 121
        port = JiveGlobals.getIntProperty("mail.smtp.port", 25);
        username = JiveGlobals.getProperty("mail.smtp.username");
        password = JiveGlobals.getProperty("mail.smtp.password");
        sslEnabled = JiveGlobals.getBooleanProperty("mail.smtp.ssl");
        debugEnabled = JiveGlobals.getBooleanProperty("mail.debug");
    }

    /**
     * Factory method to return a blank JavaMail message. You should use the
     * object returned and set desired message properties. When done, pass the
     * object to the addMessage(Message) method.
     *
Matt Tucker's avatar
Matt Tucker committed
122
     * @return a new JavaMail message.
123 124
     */
    public MimeMessage createMimeMessage() {
125 126 127
        if (session == null) {
            createSession();
        }
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
        return new MimeMessage(session);
    }

    /**
     * Sends a JavaMail message. To create a message, use the
     * {@link #createMimeMessage()} method.
     *
     * @param message the message to send.
     */
    public void sendMessage(MimeMessage message) {
        if (message != null) {
            sendMessages(Collections.singletonList(message));
        }
        else {
            Log.error("Cannot add null email message to queue.");
        }
    }

    /**
     * Send a collection of messages. To create a message, use the
     * {@link #createMimeMessage()} method.
     *
     * @param messages a collection of the messages to send.
     */
    public void sendMessages(Collection<MimeMessage> messages) {
        // If there are no messages, do nothing.
        if (messages.size() == 0) {
            return;
        }
157
        TaskEngine.getInstance().submit(new EmailTask(messages));
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    }

    /**
     * Sends a message, specifying all of its fields.<p>
     *
     * To have more advanced control over the message sent, use the
     * {@link #sendMessage(MimeMessage)} method.<p>
     *
     * Both a plain text and html body can be specified. If one of the values is null,
     * only the other body type is sent. If both body values are set, a multi-part
     * message will be sent. If parts of the message are invalid (ie, the toEmail is null)
     * the message won't be sent.
     *
     * @param toName the name of the recipient of this email.
     * @param toEmail the email address of the recipient of this email.
     * @param fromName the name of the sender of this email.
     * @param fromEmail the email address of the sender of this email.
     * @param subject the subject of the email.
     * @param textBody plain text body of the email, which can be <tt>null</tt> if the
     *      html body is not null.
     * @param htmlBody html body of the email, which can be <tt>null</tt> if the text body
     *      is not null.
     */
    public void sendMessage(String toName, String toEmail, String fromName,
            String fromEmail, String subject, String textBody, String htmlBody) 
    {
        // Check for errors in the given fields:
        if (toEmail == null || fromEmail == null || subject == null ||
                (textBody == null && htmlBody == null))
        {
            Log.error("Error sending email: Invalid fields: "
                    + ((toEmail == null) ? "toEmail " : "")
                    + ((fromEmail == null) ? "fromEmail " : "")
                    + ((subject == null) ? "subject " : "")
                    + ((textBody == null && htmlBody == null) ? "textBody or htmlBody " : "")
            );
        }
        else {
            try {
197
                String encoding = MimeUtility.mimeCharset("UTF-8");
198
                MimeMessage message = createMimeMessage();
Matt Tucker's avatar
Matt Tucker committed
199 200
                Address to;
                Address from;
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

                if (toName != null) {
                    to = new InternetAddress(toEmail, toName, encoding);
                }
                else {
                    to = new InternetAddress(toEmail, "", encoding);
                }

                if (fromName != null) {
                    from = new InternetAddress(fromEmail, fromName, encoding);
                }
                else {
                    from = new InternetAddress(fromEmail, "", encoding);
                }

                // Set the date of the message to be the current date
                SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z",
                        java.util.Locale.US);
                format.setTimeZone(JiveGlobals.getTimeZone());
                message.setHeader("Date", format.format(new Date()));
                message.setHeader("Content-Transfer-Encoding", "8bit");
                message.setRecipient(Message.RecipientType.TO, to);
                message.setFrom(from);
                message.setSubject(StringUtils.replace(subject, "\n", ""), encoding);
                // Create HTML, plain-text, or combination message
                if (textBody != null && htmlBody != null) {
                    MimeMultipart content = new MimeMultipart("alternative");
                    // Plain-text
                    MimeBodyPart text = new MimeBodyPart();
                    text.setText(textBody, encoding);
                    text.setDisposition(Part.INLINE);
                    content.addBodyPart(text);
                    // HTML
                    MimeBodyPart html = new MimeBodyPart();
235
                    html.setContent(htmlBody, "text/html; charset=UTF-8");
236
                    html.setDisposition(Part.INLINE);
237
                   html.setHeader("Content-Transfer-Encoding", "8bit");
238 239 240 241 242 243 244 245 246 247
                    content.addBodyPart(html);
                    // Add multipart to message.
                    message.setContent(content);
                    message.setDisposition(Part.INLINE);
                    sendMessage(message);
                }
                else if (textBody != null) {
                    MimeBodyPart bPart = new MimeBodyPart();
                    bPart.setText(textBody, encoding);
                    bPart.setDisposition(Part.INLINE);
248
                   bPart.setHeader("Content-Transfer-Encoding", "8bit");
249 250 251 252 253 254 255 256 257
                    MimeMultipart mPart = new MimeMultipart();
                    mPart.addBodyPart(bPart);
                    message.setContent(mPart);
                    message.setDisposition(Part.INLINE);
                    // Add the message to the send list
                    sendMessage(message);
                }
                else if (htmlBody != null) {
                    MimeBodyPart bPart = new MimeBodyPart();
258
                    bPart.setContent(htmlBody, "text/html; charset=UTF-8");
259
                    bPart.setDisposition(Part.INLINE);
260
                   bPart.setHeader("Content-Transfer-Encoding", "8bit");
261 262 263 264 265 266 267 268 269
                    MimeMultipart mPart = new MimeMultipart();
                    mPart.addBodyPart(bPart);
                    message.setContent(mPart);
                    message.setDisposition(Part.INLINE);
                    // Add the message to the send list
                    sendMessage(message);
                }
            }
            catch (Exception e) {
270
                Log.error(e.getMessage(), e);
271 272 273 274 275
            }
        }
    }

    /**
276
     * Sends a collection of email messages. This method differs from
Matt Tucker's avatar
Matt Tucker committed
277
     * {@link #sendMessages(Collection)} in that messages are sent
278 279
     * before this method returns rather than queueing the messages to be sent later.
     *
280 281
     * @param messages the messages to send.
     * @throws MessagingException if an error occurs.
282 283 284 285 286 287 288 289 290
     */
    public void sendMessagesImmediately(Collection<MimeMessage> messages)
            throws MessagingException
    {
        EmailTask task = new EmailTask(messages);
        task.sendMessages();
    }

    /**
Matt Tucker's avatar
Matt Tucker committed
291
     * Returns the SMTP host (e.g. mail.example.com). The default value is "localhost".
292
     *
293 294 295 296 297 298 299
     * @return the SMTP host.
     */
    public String getHost() {
        return host;
    }

    /**
Matt Tucker's avatar
Matt Tucker committed
300
     * Sets the SMTP host (e.g. mail.example.com). The default value is "localhost".
301 302
     *
     * @param host the SMTP host.
303 304 305
     */
    public void setHost(String host) {
        this.host = host;
306 307 308 309 310
        JiveGlobals.setProperty("mail.smtp.host", host);
        session = null;
    }

    /**
Matt Tucker's avatar
Matt Tucker committed
311 312
     * Returns the port number used when connecting to the SMTP server. The default
     * port is 25.
313 314 315 316 317
     *
     * @return the SMTP port.
     */
    public int getPort() {
        return port;
318 319 320 321 322 323
    }

    /**
     * Sets the port number that will be used when connecting to the SMTP
     * server. The default is 25, the standard SMTP port number.
     *
324
     * @param port the SMTP port number.
325 326
     */
    public void setPort(int port) {
Matt Tucker's avatar
Matt Tucker committed
327 328 329
        if (port < 0) {
            throw new IllegalArgumentException("Invalid port value: " + port);
        }
330
        this.port = port;
331 332 333 334 335 336 337 338 339 340 341 342 343
        JiveGlobals.setProperty("mail.smtp.port", Integer.toString(port));
        session = null;
    }

    /**
     * Returns the username used to connect to the SMTP server. If the username
     * is <tt>null</tt>, no username will be used when connecting to the server.
     *
     * @return the username used to connect to the SMTP server, or <tt>null</tt> if
     *      there is no username.
     */
    public String getUsername() {
        return username;
344 345 346 347
    }

    /**
     * Sets the username that will be used when connecting to the SMTP
348
     * server. The default is <tt>null</tt>, or no username.
349
     *
350
     * @param username the SMTP username.
351 352 353
     */
    public void setUsername(String username) {
        this.username = username;
354 355 356 357 358 359 360
        if (username == null) {
            JiveGlobals.deleteProperty("mail.smtp.username");
        }
        else {
            JiveGlobals.setProperty("mail.smtp.username", username);
        }
        session = null;
361 362 363
    }

    /**
364 365
     * Returns the password used to connect to the SMTP server. If the password
     * is <tt>null</tt>, no password will be used when connecting to the server.
366
     *
367 368 369 370 371 372 373 374 375 376 377 378
     * @return the password used to connect to the SMTP server, or <tt>null</tt> if
     *      there is no password.
     */
    public String getPassword() {
        return password;
    }

    /**
     * Sets the password that will be used when connecting to the SMTP
     * server. The default is <tt>null</tt>, or no password.
     *
     * @param password the SMTP password.
379 380 381
     */
    public void setPassword(String password) {
        this.password = password;
382 383 384 385 386 387 388
        if (password == null) {
            JiveGlobals.deleteProperty("mail.smtp.password");
        }
        else {
            JiveGlobals.setProperty("mail.smtp.password", password);
        }
        session = null;
389 390 391
    }

    /**
392 393 394 395 396 397 398 399 400 401 402
     * Returns true if SMTP debugging is enabled. Debug information is
     * written to <tt>System.out</tt> by the underlying JavaMail provider.
     *
     * @return true if SMTP debugging is enabled.
     */
    public boolean isDebugEnabled() {
        return debugEnabled;
    }

    /**
     * Enables or disables SMTP transport layer debugging. Debug information is
403 404 405 406 407 408
     * written to <tt>System.out</tt> by the underlying JavaMail provider.
     *
     * @param debugEnabled true if SMTP debugging should be enabled.
     */
    public void setDebugEnabled(boolean debugEnabled) {
        this.debugEnabled = debugEnabled;
409 410
        JiveGlobals.setProperty("mail.debug", Boolean.toString(debugEnabled));
        session = null;
411 412 413
    }

    /**
414 415 416 417 418 419 420 421 422 423 424
     * Returns true if SSL is enabled for SMTP connections.
     *
     * @return true if SSL is enabled.
     */
    public boolean isSSLEnabled() {
        return sslEnabled;
    }

    /**
     * Sets whether the SMTP connection is configured to use SSL or not.
     * Typically, the port should be 465 when using SSL with SMTP.
425 426 427 428 429
     *
     * @param sslEnabled true if ssl should be enabled, false otherwise.
     */
    public void setSSLEnabled(boolean sslEnabled) {
        this.sslEnabled = sslEnabled;
430 431
        JiveGlobals.setProperty("mail.smtp.ssl", Boolean.toString(sslEnabled));
        session = null;
432 433 434 435 436
    }

    /**
     * Creates a Javamail session.
     */
437 438 439 440 441
    private synchronized void createSession() {
        if (host == null) {
            throw new IllegalArgumentException("Host cannot be null.");
        }

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        Properties mailProps = new Properties();
        mailProps.setProperty("mail.smtp.host", host);
        mailProps.setProperty("mail.smtp.port", String.valueOf(port));
        // Allow messages with a mix of valid and invalid recipients to still be sent.
        mailProps.setProperty("mail.smtp.sendpartial", "true");
        mailProps.setProperty("mail.debug", String.valueOf(debugEnabled));

        // Methology from an article on www.javaworld.com (Java Tip 115)
        // We will attempt to failback to an insecure connection
        // if the secure one cannot be made
        if (sslEnabled) {
            // Register with security provider.
            Security.setProperty("ssl.SocketFactory.provider", SSL_FACTORY);

            mailProps.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            mailProps.setProperty("mail.smtp.socketFactory.fallback", "true");
        }

        // If a username is defined, use SMTP authentication.
        if (username != null) {
            mailProps.put("mail.smtp.auth", "true");
        }
        session = Session.getInstance(mailProps, null);
    }

    /**
     * Task to send one or more emails via the SMTP server.
     */
    private class EmailTask implements Runnable {

        private Collection<MimeMessage> messages;

        public EmailTask(Collection<MimeMessage> messages) {
            this.messages = messages;
        }

478
        @Override
479
        public void run() {
480 481 482 483
            try {
                sendMessages();
            }
            catch (MessagingException me) {
484
                Log.error(me.getMessage(), me);
485 486 487 488
            }
        }

        public void sendMessages() throws MessagingException {
489 490 491
            Transport transport = null;
            try {
                URLName url = new URLName("smtp", host, port, "", username, password);
492 493 494
                if (session == null) {
                    createSession();
                }
495 496 497 498 499 500 501 502 503
                transport = new com.sun.mail.smtp.SMTPTransport(session, url);
                transport.connect(host, port, username, password);
                for (MimeMessage message : messages) {
                    // Attempt to send message, but catch exceptions caused by invalid
                    // addresses so that other messages can continue to be sent.
                    try {
                        transport.sendMessage(message,
                            message.getRecipients(MimeMessage.RecipientType.TO));
                    }
504
                    catch (AddressException | SendFailedException ae) {
505
                        Log.error(ae.getMessage(), ae);
506 507 508 509 510 511 512 513 514 515 516 517 518
                    }
                }
            }
            finally {
                if (transport != null) {
                    try {
                        transport.close();
                    }
                    catch (MessagingException e) { /* ignore */ }
                }
            }
        }
    }
519
}