Sending a First E-mail

This section introduces you to the core classes you need to send an e-mail message. Specifically, you will use these classes to write code that accepts a SMTP host and mail recipient from the command line, and then sends a plain text e-mail to that recipient.

Although the application uses the command line, you can modify the code for use in other situations if you want. For example, you could modify the code so that it accepts parameters from another application or presents the user with a desktop or applet GUI written using Swing or AWT.

Creating a First E-mail

Now that you have set up your development environment, you can write the code that will send an e-mail message. This application uses classes from the javax.mail package and the javax.mail.internet package. The javax.mail package provides classes that model a mail system, for example all mail systems require messages to contain a message body. The javax.mail.internet package provides classes that are specific to Internet mail systems, for example, a class that allows you to manipulate the content type of a message. This application commences by importing both of these packages and java.util.Properties, which allows you to set the SMTP host as a system property.

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

Because this is a simple application, the main() method contains all the code to collect user input and send the e-mail message. In this example, the user will pass three parameters to the application via the command line—SMTP host, recipient's e-mail address, and sender's e-mail address:

public class SendMail {
    public static void main(String[] args) {
        if (args.length!=3) {
System.out.println ("Usage: SendMail SMTPHost ToAddress FromAddress");
            System.exit(1);
        }

        String smtpHost=args[0];
        String to=args[1];
        String from = args[2];

Before you can create and send an e-mail message, you must have authenticated access to a SMTP host. If you are unsure of your SMTP host, either check with your system administrator or obtain the host address from the configuration of an e-mail application. To help you identify the host, the naming conventions for hosts means that your SMTP host is likely to take the form of smtp.host or mail.host. After you identify the SMTP host, you must make it available as a system property to the JVM. To do this, you must add the host name to the system properties list:

Properties props = System.getProperties();
props.put("mail.smtp.host",smtpHost);

The first line of code gets a Properties object that represents the system properties. The code then writes a key/value pair to the system properties list. The first argument of the put() method, mail.smtp.host, is defined by Appendix A of the JavaMail specification. Table 11.1 shows all of the properties the specification defines.

Table 11.1. Mail Environment Properties
Property Description
mail.store.protocol Specifies the default message access protocol. The default value is the first appropriate protocol in the mail configuration files.
mail.transport. protocol Specifies the default mail transport protocol. The default value is the first appropriate protocol in the mail configuration files.
mail.host Specifies the default mail server. The default value is the local machine.
mail.user Specifies the default username used when connecting to the mail server. The default value is user.name.
mail.protocol.host Specifies the protocol-specific mail server. This property overrides any value you specify for mail.host. The default value is mail.host.
mail.protocol.user Specifies the protocol-specific username used when connecting to the mail server. This property overrides the value of mail.user. The default value is mail.user.
mail.from Specifies the return address of the current user. The default value is username@host.
mail.debug Specifies whether debug is enabled or disabled. The default value is false—debug is disabled.

In this example, you overrode the value of mail.protcol.host, which in turn overrides the value of mail.host.

Now that the code defines a Properties object containing the SMTP host, you create a mail session. A Session object represents the mail session, and all e-mail functionality works through this object. The Session object has two private constructors. The first provides a unique mail session that applications cannot share. To get this type of session you call the getInstance() method:

Session session = Session.getInstance(props, null);

In this example, the first argument is the Properties object that you previously created. The second argument, null, is an Authenticator object, which today's lesson discusses later in the “Authenticating Users and Security” section. The second constructor also takes these arguments, but it differs in that it creates a Session object that applications can share. It is this type of Session your first e-mail application uses:

Session session = Session.getDefaultInstance(props, null);

After you create a Session, you can start creating an e-mail message. The Message class represents an e-mail message, but it is an abstract class, so you must implement a subclass. The JavaMail API defines only one subclass, MimeMessage, that represents a standard MIME style e-mail message. The class has five constructors, but you will only use one of these at the moment—the default constructor. This accepts a single parameter—a Session object:

MimeMessage message = new MimeMessage(session);

This creates an empty MimeMessage object. You must now fill the object with appropriate attributes and content—in this example, subject, message text, from address, and to address. The MimeMessage class exposes a large number of methods for getting and settings these attributes. Today, you will explore several of these methods, but for a complete guide, refer to the API documentation. In this example, you first set the text of the message by using the setText() method:

message.setText("Hi from the J2EE in 21 Days authors");

The setText() method not only sets the message's text, but it also sets the content type of the message to text/plain. If the content is not of the type text/plain, you must first use the setContent() method to set the message's content type—you will learn how to do this later today in the “Authenticating Users and Security” section. The setText() method throws an exception of the type MessagingException, which is the base class for all messaging class exceptions. The majority of the methods associated with the mail packages throw this exception or one of its subclasses, so inevitably you have to catch these exceptions.

To set the subject of the message, you use the setSubject() method, which takes a string representing the subject as a parameter:

message.setSubject("Hi!");

The message now requires the addresses of the recipient and sender. To set the sender's address, you use the setFrom() method. The method takes a single argument of the type Address. The Address class represents an address in an e-mail message. The class is abstract, so you must use one of its subclasses, namely InternetAddress. This class has four constructors; the one you use takes a single parameter—an e-mail address as a string:

message.setFrom(new InternetAddress(from));

You provide the recipient's address to the MimeMessage object in a similar way. But you must also stipulate to which type of recipient the address relates. The Message class has one inner class, RecipientType, that defines the type of recipient within an e-mail message. The class exposes three fields that relate to the different recipient types:

  • BCC— Blind carbon copy recipients

  • CC— Carbon copy recipients

  • TO— TO recipients

In this application, you only send the message to one recipient, so you use the TO field. When you set the from address, you used the setFrom() method, and you use the addRecipient() method to set the To address. The code to set the recipient's address appears as follows:

message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));

You have now created the message, now you must send the message. The Transport class, which models an e-mail transport system, provides you with the means to send the message. The class provides two static send() methods that send messages. The first form takes a Message object and an array of Address objects as arguments. It sends the message to all the recipients the Address objects define and ignores any addresses the message defines. The second version of this method takes one parameter—a Message object. Note that the Message object must define at least one recipient's address. It is this method you will now use:

Transport.send(message);

The send() method may throw a MessagingException or a SendFailedException. The SendFailedException is thrown if the send() method fails to send one or more messages. The exception traceback includes a list of all the e-mail addresses to which it could not send messages.

You have now completed the code to send an e-mail. Listing 11.1 shows the complete code:

Listing 11.1. SendMail.java Full Listing
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class SendMail {
    public static void main(String[] args) {
        if (args.length!=3) {
            System.out.println("Usage: SendMail SMTPHost ToAddress FromAddress");
            System.exit(1);
        }

        String smtpHost = args[0];
        String to = args[1];
        String from = args[2];

        // Get properties object
        Properties props = System.getProperties();

        // Define SMTP host property
        props.put("mail.smtp.host",smtpHost);

        try {
            // Get a session
            Session session = Session.getDefaultInstance(props,null);

            // Create a new message object
            MimeMessage message = new MimeMessage(session);

            // Populate message object
            message.setText("Hi from the J2EE in 21 Days authors.");
            message.setSubject("Hi!");
            message.setFrom(new InternetAddress(from));
message.addRecipient (Message.RecipientType.TO,new InternetAddress(to));
            System.out.println("Message Sent");

            // Send the message
            Transport.send(message);
        }
        catch (MessagingException me) {
            System.err.println(me.getMessage());
        }
    }
}
						

To run this application, you must first compile it. Compile it from the command line using javac as you would for any other Java application. After it compiles, run the application by issuing the following command:

java SendMail mail.yourSMTPHost.com toAddress fromAddress

When the program executes, a Message Sent message should display. If the program fails to execute correctly, check the error messages the JVM displays. The most likely cause of failure is an incorrect SMTP host or one that is inaccessible from your system. There are several ways you can check whether the host exists and is visible. For example, you can run a trace route to your SMTP host; under Windows (all versions) issue the following command at the command prompt:

tracert yourSMTPHost

On Unix or Linux systems, use the following:

traceroute yourSMTPHost

If the host does not exist or is inaccessible, you will receive a message indicating that your trace route program could not resolve the hostname you specified, or on some systems, the displayed route will suddenly die.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.227.9