DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Email 101

02.27.2006
| 11850 views |
  • submit to reddit
        I'm leaving this code here but I'm recommending against its use. The Jakarta 
Commons Email library (http://jakarta.apache.org/commons/email/) is a better 
choice. It's just as easy to use but it also has support for more features 
of sending email and it will handle one thing in particular that is difficult
to get right on your own.

If you want to send an email with embedded graphics and include all those
graphics in the email (i.e. they aren't just links to graphics on some remote
server) then the Commons Email library will let you do that easily. Trust me,
it beats having to figure out how to do it yourself in a way that works
across email clients.




// This example of sending mail is a little different from the typical one you
// see in Java. For one thing, when you call the function to send the email
// you send in both a plain text version of the email and an HTML version. The
// recipient's email reader will pick the version to display (usually favoring
// the HTML version if it can display both).
// 
// The other thing to note is that there is some commented out code in the 
// method for dealing with SMTP servers which require authentication. As best
// I can remember this code worked fine but it's not in the current version.

// Copyright (c) 2002, John Munsch
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without 
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice, 
//       this list of conditions and the following disclaimer.
// 
//     * Redistributions in binary form must reproduce the above copyright 
//       notice, this list of conditions and the following disclaimer in the 
//       documentation and/or other materials provided with the distribution.
// 
//     * Neither the name of the John Munsch nor the names of its contributors 
//       may be used to endorse or promote products derived from this software 
//       without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
// POSSIBILITY OF SUCH DAMAGE.
// 
// To learn more about open source licenses, please visit: 
// http://opensource.org/index.php

package com.johnmunsch.util;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

import org.apache.log4j.*;

/**
 * Handles sending email to a user. Slightly different from some of the examples
 * you see in that it will send a multi-format email with both a HTML "pretty"
 * version of the email and a straight text version.
 */
public class Mail {
    private static Logger log = Logger.getLogger(Mail.class.getName());
    
    /**
     * Send an email from one user to another user with a given subject using a
     * given SMTP host. You can send both text and HTML versions of the same
     * email, and it should in fact be the same email content in both cases,
     * because the end user's email program will be the one to pick the version
     * to display to the user.
     * 
     * @param from
     * @param to
     * @param subject
     * @param textBody
     * @param htmlBody
     * @param host
     * @throws AddressException
     * @throws MessagingException
     */
    public static void sendMail(String from, String to, String subject, 
            String textBody, String htmlBody, String host) 
            throws AddressException, MessagingException {
        // Get system properties.
        Properties props = System.getProperties();

        // Setup the mail server.
        props.put("mail.smtp.host", host);

        // Get a session.
        Session session = Session.getInstance(props, null);

        // The following is required for SMTP servers that require 
        // authentication in order to send an email.
//        Transport transport = session.getTransport("smtp");
//        transport.connect(host, username, password);
//        props.put("mail.smtp.auth", "true");

        // Define the message.
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, 
          new InternetAddress(to));
        message.setSubject(subject);
        message.setText(textBody);

        message.setContent(htmlBody, "text/html");

        // Send message
        Transport.send(message);
    }
}