Java Mail Debug Utility Source Code
Posted by William Brant on Tue, May 31, 2011 @ 07:31 PM
Source Code for the Java Mail Debug Utility below.
package com.dsi.test;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class MailDebug {
public static void main(String[] args) {
// Create properties, get Session
Properties props = new Properties();
// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
String to = args[0];
String from = args[1];
// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
String host = args[2];
String username="";
String password="";
int port=25;
if (null!=args[3])
{
username = args[3];
props.put("mail.smtp.user", username);
}
if (null !=args[4])
{
password = args[4];
props.put("mail.smtp.password", username);
props.put("mail.smtp.auth", "true");
}
// If using static Transport.send(),
// need to specify which host to send it to
props.put("mail.smtp.host", host);
// To see what is going on behind the scene
props.put("mail.debug", "true");
// Session session = Session.getInstance(props);
Session session = Session.getDefaultInstance(props, null);
System.out.println(props.toString());
try {
// Instantiates a message
Message msg = new MimeMessage(session);
//Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Test E-Mail through Java");
msg.setSentDate(new Date());
// Set message content
msg.setText("This is a test of sending a " +
"plain text e-mail through Java.\n" +
"Here is line 2.");
Transport transport = session.getTransport("smtp");
transport.connect(host, username, password);
if (null!=args[4])
{
System.out.println("Sending with Authentication using :"+ username+" and Password"+password);
//transport.connect(host, port, username, password);
transport.sendMessage(msg, msg.getAllRecipients());
// transport.send(msg);
}
else
{
//Send the message
System.out.println("Sending without Authentication");
transport.sendMessage(msg, msg.getAllRecipients());
//transport.send(msg);
}
}
catch (Exception ex) {
// Prints all nested (chained) exceptions as well
// ex.printStackTrace();
System.out.println(ex.toString());
}
}
}