Never been to DZone Snippets before?

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

About this user

John Munsch http://www.johnmunsch.com

« Newer Snippets
Older Snippets »
Showing 11-13 of 13 total

Email 101 Unit Tests

// Two unit tests for my Email 101 code. The first expects connection information to
// be in the System properties. That can be setup as part of running the unit tests
// from either Ant or Eclipse. Note: The first test only confirms that the send occurs
// without error, not that the email was actually received or received at the correct
// address.
//
// The second test trashes the SMTP server name and then confirms that it results in
// an exception being thrown from the mail sending code.

package com.johnmunsch.util;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import junit.framework.TestCase;

public class MailTest extends TestCase {
    String from = null;
    String to = null;
    String title = null;
    String textBody = null;
    String htmlBody = null;
    String smtpServer = null;
    
    /* (non-Javadoc)
     * @see junit.framework.TestCase#setUp()
     */
    protected void setUp() throws Exception {
        from = System.getProperty("from");
        to = System.getProperty("to");
        title = System.getProperty("title");
        textBody = System.getProperty("textBody");
        htmlBody = System.getProperty("htmlBody");
        smtpServer = System.getProperty("smtpServer");
    }

    /**
     * This is a terrible test. It could fail just as easily because it is 
     * incorrectly supplied with parameters as due to any failure in the code.
     * @throws MessagingException 
     * @throws AddressException 
     */
    public void testSendMail() throws AddressException, MessagingException {
        Mail.sendMail(from, to, title, textBody, htmlBody, smtpServer);
    }
    
    /**
     * Same test as above except that we screw up the smtpServer address so it
     * is absolute garbage. In that case we should see a failure, which we are
     * looking for, and we throw an error if we _don't_ see some kind of
     * exception.
     */
    public void testSendMailWithBadServer() {
        smtpServer = "garbageingarbageout";
        
        try {
            Mail.sendMail(from, to, title, textBody, htmlBody, smtpServer);
            
            fail();
        } catch (AddressException e) {
            // Exception good, no exception bad.
        } catch (MessagingException e) {
            // Exception good, no exception bad.
        }
    }
}

Email 101

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);
    }
}

Velocity 101

// The most basic use of the Velocity library. You pass in a Velocity context
// containing key-value pairs and the name of a Velocity template file. It
// returns a string containing the boilerplate text generated from combining
// the two.

// 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.io.StringWriter;

import org.apache.log4j.*;
import org.apache.velocity.*;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.*;

/**
 * Boilerplate puts together context information and a template and produces an
 * output string that has all the replacements done in it.
 */
public class Boilerplate {
    private static Logger log = Logger.getLogger(Boilerplate.class.getName());
    
    public static String apply(VelocityContext context,
            String templateFilename) throws Exception {
        Template template = null;
        StringWriter sw = new StringWriter();

        Velocity.init();

        try {
            template = Velocity.getTemplate(templateFilename);

            template.merge(context, sw);
        } catch (ResourceNotFoundException rnfe) {
            log.error("Could not find the named template file.", rnfe);
            throw rnfe;
        } catch (ParseErrorException pee) {
            log.error("Error in the template file.", pee);
            throw pee;
        } catch (MethodInvocationException mie) {
            log.error("Error in function called by the template file.", mie);
            throw mie;
        }
       
        return sw.toString();
    }
}
« Newer Snippets
Older Snippets »
Showing 11-13 of 13 total