Sending E-mails with Attachments

In the previous example, you used MIME multi-part messages to send a HTML message that displays an image. Another use of MIME is to send message attachments, such as MPEG videos, JPEG images, and plain text files. In this example, you will create a small command line application that sends a message with an attached XML file to a named recipient.

The code for this application is very similar to the previous applications. Today's lesson only explores those sections of code that differ from the previous examples, but you can still find a full listing at the end of this section or on the CD-ROM that accompanies this book.

This application starts by creating Properties, Session, and MimeMessage objects. It also adds the message subject, sender's address, and recipient's address to the MimeMessage object. You must then create an empty BodyPart object, using the same technique as the previous example:

BodyPart messageBodyPart = new MimeBodyPart();

This is the first part of the message. You will create another part in a moment that will contain the file attachment. Before you do this, use the setText() method you used in previous examples to set the message's body text:

messageBodyPart.setText("Here's an attachment!");

Now you must create a new MimeMultipart object to hold the two parts of the message. In the previous example, you passed an argument of related (the MIME subtype) to the MimeMultipart constructor. This was because the different body parts connected to form a compound object, but in this example, the attachment does not integrate with the message body. The subtype in this example is multipart/mixed. This subtype is the default for the constructor, so you do not have to explicitly pass it to the constructor:

Multipart multipart = new MimeMultipart();

Now that you have created the MimeMultipart object, you can add the first of the body parts to it. Simply use the addBodyPart() method, as you did in the previous application:

multipart.addBodyPart(messageBodyPart);

That is the first part of the message. You must now create the body part that contains the attachment and add it to the MimeMultipart object. The previous example set a data handler for the body part; the data handler referenced a DataSource object that encapsulated an image file. You use exactly the same approach with an attachment:

// Create an empty body part
messageBodyPart = new MimeBodyPart();

// Create a new DataSource, passing it the attachment file
DataSource source = new FileDataSource(fileName);

// Set the data handler
messageBodyPart.setDataHandler(new DataHandler(source));

The final step before adding the body part to the MimeMultipart object is to set the filename that associates with this body part. To do this, you use the MimeBodyPart's setFileName() method that takes one argument, a string representing the filename. One other point to note about this method is that it might throw one of three exceptions: MessagingException, javax.mail.IllegalWriteException (descended from MessagingException), or java.lang.IllegalStateException. An IllegalWriteException occurs when the underlying implementation can be modified, and an IllegalStateException occurs when the body part is obtained from a read only directory.

// associate the file name
messageBodyPart.setFileName(fileName);
// add body part to MimeMultipart object
multipart.addBodyPart(messageBodyPart);

The remaining code is identical to the previous example. Listing 11.4 shows the complete code for this application.

Listing 11.4. SendAttachmentMail.java Full Listing
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

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

        String smtpHost = args[0];
        String to = args[1];
        String from = args[2];
        String contentType = "text/html";
        String fileName = args[3];

        // 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.setSubject("Hi!");
            message.setFrom(new InternetAddress(from));
message.addRecipient (Message.RecipientType.TO,new InternetAddress(to));

            // Create the message body part
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText("Here's an attachment!");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // Create the attachment body part
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(fileName);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);

            // Put parts in message
            message.setContent(multipart);

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

The code for this application is now complete. To run this application, you must first compile it. When compiled, run the application by issuing the following command:

java SendAttachmentMail mail.yourSMTPHost.com toAddress fromAddress attachment

If you don't have a file to attach at hand, the CD-ROM accompanying this book contains a small XML file that is appropriate for this purpose.

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

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