Pages

Saturday, March 31, 2012

How to automate Email testing

If you are looking for a solution to automate the email testing i.e.. sending an email and verifying the reception, I prefer using WISER a dummy email server:

Wiser:


Wiser is a simple SMTP server that you can use for unit testing applications that send mail. It accepts all messages and stores them in an internal ArrayList. Your unit test code can then examine the messages (or lack thereof) and verify their validity.
WISER IS NOT A MAIL SERVER. If you want to receive email and then "do something" with the mail, simply implement the MessageHandler or MessageListener interfaces. Look at the (very short) Wiser code as an example.

How To Use It

Include the following jars on your classpath:
  • subethasmtp.jar
  • slf4j-api-X.X.X.jar
  • One of the slf4j connectors such as slf4j-simple-X.X.X.jar
  • JavaMail (mail.jar and activation.jar) 
Start the WISER server using below code. Now send the email from your application to the below address. Example: username@localhost.com.

Sample code:


package com.ca.example;

import org.junit.*;
import org.subethamail.wiser.Wiser;
import org.subethamail.wiser.WiserMessage;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 public class WiserJUnitTest {

    private Wiser wiser;

    @Before
    public void setup() {
        wiser = new Wiser(2500);
        wiser.setHostname("localhost");
        wiser.setPort(2500);
        wiser.start();
        System.out.println("Wiser SMTP server started.");

    }

    @Test
    public void sendTest() throws Exception {
      
    /**
     * Creating and sending an email using Java Mail API
     */
        Properties props = new Properties();
        props.put("mail.smtp.host", "localhost");
        props.put("mail.smtp.port", "2500");
        props.put("mail.smtp.user", "username");
        props.put("mail.smtp.password", "password");

        Session session = Session.getInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("from@company.com"));
        message.setRecipients(Message.RecipientType.TO,
        InternetAddress.parse("to@company.com"));
        message.setSubject("Testing Subject");
        message.setText("This is just a test e-mail! ");
        message.setHeader("Organization", "company.com");
    
//        Transport.send(message);
        System.out.println("Done sending this email :" + message);
      
        System.out.println("Wiser messages count:"+wiser.getMessages().size());
        Assert.assertEquals("No mail messages found", 1, wiser.getMessages().size());

       if (wiser.getMessages().size() > 0) {
        WiserMessage wMsg = wiser.getMessages().get(0);
       
        MimeMessage msg = wMsg.getMimeMessage();
        System.out.println( msg.getSubject() );
        }

Good Luck!!!