Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

  Tutorial: JavaMail quick start

JavaMail quick start

Tutorial Details:

JavaMail quick start
JavaMail quick start
By: By Tony Loton
Send and receive email with the JavaMail APIs
n JavaMail you'll find APIs and provider implementations allowing you to develop fully functional email client applications. "Email client applications" invokes thoughts of Microsoft Outlook; and, yes, you could write your own Outlook replacement. But an email client need not reside on a client machine at all. Indeed, it could be a servlet or an EJB running on a remote server, providing end-user access to email via a Web browser. Think of Hotmail (yes, you could write your own version of Hotmail too). Or you could avoid a user interface altogether. How about an auto-responder that reads incoming messages and sends replies, customized according to the original sender?
In my own pet project, a talking email client reads -- that is, speaks -- incoming messages. It's based on a refinement of an idea I introduced in " Talking Java! " I'll tell you more about it later.
For now, start by installing and configuring the JavaMail software.
Setup
If you use Java 2 Platform, Enterprise Edition (J2EE) 1.3, you're in luck: it includes JavaMail, so no additional setup is required. If, however, you're running Java 2 Platform, Standard Edition (J2SE) 1.1.7 and upwards, and you want email capability for your applications, download and install the following:
JavaMail
JavaBeans Activation Framework
To install, simply unzip the downloaded files and add the contained jar files to your classpath. As an example, here's my classpath for this project:
.;C:\Apps\Java\javamail-1.2\mail.jar;C:\Apps\Java
\javamail-1.2\mailapi.jar;C:\Apps\Java\javamail-1.2
\pop3.jar;C:\Apps\Java\javamail-1.2\smtp.jar;C:\Apps
\Java\jaf-1.0.1\activation.jar
The mailapi.jar file contains the core API classes, while the pop3.jar and smtp.jar files contain the provider implementations for the respective mail protocols. (We won't use the imap.jar file in this article.) Think of the provider implementations as similar to JDBC (Java Database Connectivity) drivers, but for messaging systems rather than databases. As for the mail.jar file, it contains each of the above jar files, so you could restrict your classpath to just the mail.jar and activation.jar files.
The activation.jar file allows you to handle MIME (Multipurpose Internet Mail Extensions) types accessible via binary data streams. Look for the DataHandler class in the Not Just Plain Text section later.
For the record, the rest of this article does not offer comprehensive API coverage; rather, you will learn by doing. If it's in-depth API information you're looking for, then look at the PDF files and Javadocs included in the respective download bundles.
Once you've installed the software, you need to get email account details to run the examples that follow. You'll need your ISP's SMTP (Simple Mail Transfer Protocol) server name and POP (Post Office Protocol) server name, your email account login name, and your mailbox password. Figure 1 shows my details -- not the real ones, you understand -- as used by Microsoft Outlook.
Figure 1. Tony's Internet mail settings
Sending email via SMTP
The first example shows how to send a basic email message via SMTP. Below, you'll find the SimpleSender class, which takes your message's details from the command line and calls a separate method -- send(...) -- to send it:
package com.lotontech.mail;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
/**
* A simple email sender class.
*/
public class SimpleSender
{
/**
* Main method to send a message given on the command line.
*/
public static void main(String args[])
{
try
{
String smtpServer=args[0];
String to=args[1];
String from=args[2];
String subject=args[3];
String body=args[4];
send(smtpServer, to, from, subject, body);
}
catch (Exception ex)
{
System.out.println("Usage: java com.lotontech.mail.SimpleSender"
+" smtpServer toAddress fromAddress subjectText bodyText");
}
System.exit(0);
}
Next, run SimpleSender as below. Replace smtp.myISP.net with your own SMTP server, as derived from your mail settings:
> java com.lotontech.mail.SimpleSender smtp.myISP.net bill@lotontech.com ben@lotontech.com "Hello" "Just to say Hello."
And, if it works, at the receiving end you'll see something like what's shown in Figure 2.
Figure 2. Message received from SimpleSender
The send(...) method completes the SimpleSender class. I'll show the code first, then detail the theory:
/**
* "send" method to send the message.
*/
public static void send(String smtpServer, String to, String from
, String subject, String body)
{
try
{
Properties props = System.getProperties();
// -- Attaching to default Session, or we could start a new one --
props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props, null);
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));
// -- We could include CC recipients too --
// if (cc != null)
// msg.setRecipients(Message.RecipientType.CC
// ,InternetAddress.parse(cc, false));
// -- Set the subject and body text --
msg.setSubject(subject);
msg.setText(body);
// -- Set some other header information --
msg.setHeader("X-Mailer", "LOTONtechEmail");
msg.setSentDate(new Date());
// -- Send the message --
Transport.send(msg);
System.out.println("Message sent OK.");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
First, notice that you're obtaining a mail session ( java.mail.Session ), without which you can do nothing. In this case you're calling Session.getDefaultInstance(...) to get a shared session, which other desktop applications may reuse; you can also set up an entirely new session -- via the Session.getInstance(...) method -- that would be unique to your application. The latter could prove important for email clients not isolated on a per-user basis, such as a Web-based email system implemented with servlets.
Establishing a session requires you to set certain properties; at minimum, you need the mail.smtp.host property if you're sending messages via SMTP. You'll find other properties described within the API documentation.
Once you have a session, create a message. In this example, you're setting the message's from and to email addresses, the subject, and the body text, all taken originally from the command line. You're also setting some header information, including the date, and you can specify cc recipients if you want.
Finally, you send the message via the javax.mail.Transport class. If you wonder how it knows about our mail session, look back at the message's constructor.
Not just plain text
The setText(...) convenience method in class javax.mail.Message (inherited from the javax.mail.Part interface) sets the message content to the supplied string and sets the MIME type to text/plain .
You're not limited to plain text, though: you can send other content types via the setDataHandler(...) method. In most cases you can take "other content types" to mean file attachments, such as Word documents, but for something a bit more interesting, check out this code for sending a Java serialized object:
ByteArrayOutputStream byteStream=new ByteArrayOutputStream();
ObjectOutputStream objectStream=new ObjectOutputStream(byteStream);
objectStream.writeObject(theObject);
msg.setDataHandler(new DataHandler( new ByteArrayDataSource( byteStream.toByteArray(), "lotontech/javaobject" )));
You won't find the DataHandler class within the javax.mail.* package structure because it belongs to the JavaBeans Activation Framework (JAF) package javax.activation . Remember, you downloaded the JAF distribution as well as JavaMail. JAF provides a mechanism for handling typed data content, which for Internet content means MIME types.
And if you really do try the code above for sending a Java object by email, you'll have trouble locating the ByteArrayDataSource class, as neither mail.jar nor activation.jar include it. Try looking in the JavaMail demo directory!
As for those file attachments that you're more likely to be interested in initially, you would create a javax.activation.FileDataSource instance in the DataHandler 's constructor. Of course, you're not likely to send a file alone; rather, it will probably be an attachment to a text message. For that you need to understand the concept of multipart messages, so I'll introduce that concept now, in the context of receiving email.
Receive email via POP3
Earlier, I introduced the javax.mail.Part interface implemented by javax.mail.Message . I'll now explain its message parts, which are important in this example. To start, take a look at Figure 3.
Figure 3 shows a Message as created in the previous example that is both a message and message part, because it implements the Part interface. For any part, you can get its content (any Java object), and, in the case of a simple text message, the content object may be a String . For a multipart message, the content will be of type Multipart , from which we can get hold of the individual body parts, which themselves implement the Part interface.
Figure 3. UML diagram for the mail.Part interface
In practice, all will become apparent as you step through the code for a SimpleReceiver class, which I'll present in three sections: first, the class definition and the main(...) method that takes connection details from the command line; second, the receive(...) method that captures and steps through the incoming messages; and finally, the printMessage(...) method that prints the header information and content of each message.
Here's the first section:
package com.lotontech.mail;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
/**
* A simple email receiver class.
*/
public cla


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
JavaMail quick start

View Tutorial:
JavaMail quick start

Related Tutorials:

Start customizing Swing's editor pane -- patch the Swing HTMLEditorKit - JavaWorld - January 1999
Start customizing Swing's editor pane -- patch the Swing HTMLEditorKit - JavaWorld - January 1999
 
Smarter Java development - JavaWorld August 1999
Smarter Java development - JavaWorld August 1999
 
Make room for JavaSpaces, Part 3 - JavaWorld March 2000
Make room for JavaSpaces, Part 3 - JavaWorld March 2000
 
Which JSP book serves up the best lesson?
Which JSP bookAs for Web servers/databases, just mentioning a server in the book is not sufficient to be listed here.
 
Talking Java! - JavaWorld August 2001
Talking Java! - JavaWorld August 2001
 
JavaMail quick start
JavaMail quick start
 
Create email-based apps with JAMES
Create email-based apps with JAMES
 
Create a quick-and-dirty XML parser
Create a quick-and-dirty XML parser
 
Transform data into Web applications with Cocoon
Transform data into Web applications with Cocoon
 
Update distributed applications
Update distributed applications
 
Test email components in your software
Test email components in your software
 
Joott Quick Start Guide
Joott Quick Start Guide JooTemplates is a templating system to generate business documents, such as forms, mailings and reports. It is being developed with the following aims
 
Java programming dynamics, Part 7: Bytecode engineering with BCEL
Java programming dynamics, Part 7: Bytecode engineering with BCEL Apache BCEL lets you get to the details of JVM assembler language for classworking The Apache Byte Code Engineering Library (BCEL) lets you dig into the bytecode of Java classes. You
 
Aspirin - embeddable java smtp server
Aspirin - embeddable java smtp server What is it? Aspirin is an embeddable send-only SMTP server. Why would I want that? The JavaMail API doesn't really let you send mail. And that's just annoying. Developers shouldn't have to jump through hoops t
 
The HTML Renderer Shootout, Part 1
The HTML Renderer Shootout, Part 1 In this article, we will review 11 different HTML renderers, comparing their features, compliance, and speed; searching for the best one for any project.
 
Very interesting tutorial
Introducing the JavaMail API The JavaMail API is an optional package (standard extension) for reading, composing, and sending electronic messages. You use the package to create Mail User Agent (MUA) type programs, similar to Eudora, Pine, and Microsoft O
 
Create Intelligent E-mail Filters with JavaMail and Classifier4j
Create Intelligent E-mail Filters with JavaMail and Classifier4j Tired of the limitations and annoying false positives with commercial spam filters? Classifier4J is an open source Java library that will let you build custom applications that read e-mails
 
HA-JavaMail: High-Availability JavaMail
HA-JavaMail: High-Availability JavaMail Introduction HA-JavaMail is a JavaMail transport proxy that adds efficiency and reliability to an underlying JavaMail provider. HA-JavaMail is NOT an SMTP implementation - it's a wrapper around an existing imp
 
Practically Groovy: JDBC programming with Groovy
Take your practical knowledge of Groovy one step further this month, as Andrew Glover shows you how to use GroovySql to build a simple data-reporting application. GroovySql combines closures and iterators to ease Java Database Connectivity (JDBC) programm
 
Chat Transcript: Solving the Device Fragmentation Problem
Read the questions that your fellow developers had about the new feature in NetBeans Mobility Pack 4.0 that helps solve device fragmentation problems, and the answers straight from the engineers who created the module.
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.