package com.blinco.wave3x.email;
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
/**
* This class help us to send out an e-mail with the subject and content
*/
public final class Email {
public static void main( String... aArguments ){
Email emailer = new Email();
//the domains of these email addresses should be valid,
//or the example will fail:
emailer.sendEmail(
"xibrian@yahoo.ca", "xibrian@yahoo.ca",
"Testing 1-2-3", "blah blah blah"
);
}
/**
* the private static variable
*/
private static Properties fMailServerConfig = new Properties();
/**
* Send a single email.
*/
public void sendEmail(
String aFromEmailAddr, String aToEmailAddr,
String aSubject, String aBody
){
Session session = Session.getDefaultInstance( fMailServerConfig, null );
MimeMessage message = new MimeMessage( session );
try {
message.addRecipient(
Message.RecipientType.TO, new InternetAddress(aToEmailAddr)
);
message.setSubject( aSubject );
message.setText( aBody );
String protocol = "smtp";
fMailServerConfig.put("mail." + protocol + ".auth", "true");
Transport t = session.getTransport(protocol);
try {
t.connect("ppbrian@yahoo.ca", "rtrew");
t.sendMessage(message, message.getAllRecipients());
} finally {
t.close();
}
}
catch (MessagingException ex){
System.err.println("Cannot send email. " + ex);
}
}
/**
* Allows the config to be refreshed at runtime, instead of
* requiring a restart.
*/
public static void refreshConfig() {
fMailServerConfig.clear();
fetchConfig();
}
static {
fetchConfig();
}
/**
* Open a specific text file containing mail server
* parameters, and populate a corresponding Properties object.
*/
private static void fetchConfig() {
InputStream input = null;
try {
//If possible, one should try to avoid hard-coding a path in this
//manner; in a web application, one should place such a file in
//WEB-INF, and access it using ServletContext.getResourceAsStream.
//Another alternative is Class.getResourceAsStream.
//This file contains the javax.mail config properties mentioned above.
input = new FileInputStream( "C:\\mail\\MyMailServer.txt" );
fMailServerConfig.load( input );
}
catch ( IOException ex ){
System.err.println("Cannot open and load mail server properties file.");
}
finally {
try {
if ( input != null ) input.close();
}
catch ( IOException ex ){
System.err.println( "Cannot close mail server properties file." );
}
}
}
}
exception : Cannot send email. javax.mail.MessagingException: Could not connect to SMTP host:
www.yahoo.ca, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: connect