Javamail Quick Start

Source: Internet
Author: User
Tags email account microsoft outlook

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 cocould write your own Outlook replacement. but an email client need not reside on a client machine at all. indeed, it cocould be a servlet or an EJB running on a remote server, providing end-user ac Cess to email via a Web browser. think of Hotmail (yes, you cocould write your own version of Hotmail too ). or you coshould 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 locking ing the JavaMail software.

Setup
If you use Java 2 platform, Enterprise Edition (J2EE) 1.3, you're in luck: it includes des 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

. 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

Themailapi.jarFile contains the core API classes, whilepop3.jarAndsmtp.jarFiles contain the provider implementations for the respective mail protocols. (We won't useimap.jarFile in this article.) Think of the provider implementations as similar to JDBC (Java database connectivity) drivers, but for messaging systems rather than databases. As formail.jarFile, it contains each of the above jar files, so you cocould restrict your classpath to justmail.jarAndactivation.jarFiles.

Theactivation.jarFile allows you to handle mime (Multipurpose Internet Mail Extensions) types accessible via binary data streams. Look forDataHandlerClass inNot just plain textSection 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 encoded 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

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 findSimpleSenderClass, which takes your message's details from the command line and Calla 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);
  }

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, runSimpleSenderAs below. Replacesmtp.myISP.netWith 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."

> 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 processing ing end you'll see something like what's shown in Figure 2.

Figure 2. Message received ed from simplesender

Figure 2. Message received ed from simplesender

Thesend(...)Method completesSimpleSenderClass. 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();
    }
  }
}

/**
* "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 cocould 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.,
InternetAddress. parse (to, false ));

// -- We cocould 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 callingSession.getDefaultInstance(...)To get a shared session, which other desktop applications may reuse; you can also set up an entirely new session -- viaSession.getInstance(...)Method -- That wocould be unique to your application. The latter cocould 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 needmail.smtp.hostProperty 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'sFromAndToEmail addresses,Subject,AndBodyText, all taken originally from the command line. You're also setting some header information, including the date, and you can specifyCCRecipients if you want.

Finally, you send the message viajavax.mail.TransportClass. If you wonder how it knows about our mail session, look back at the message's constructor.

Not just plain text
ThesetText(...)Convenience method in classjavax.mail.Message(Inherited fromjavax.mail.PartInterface) sets the message content to the supplied string and sets the MIME typetext/plain.

You're not limited to plain text, though: you can send other content types viasetDataHandler(...)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" )));

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 findDataHandlerClass withinjavax.mail.*Package structure because it belongs to the JavaBeans Activation Framework (JAF) packagejavax.activation. Remember, you downloaded the JAF distribution as well as JavaMail. JAF provides a mechanic for handlingTypedData 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 locatingByteArrayDataSourceClass, as neithermail.jarNoractivation.jarInclude it. Try looking in the JavaMail demo directory!

As for those file attachments that you're more likely to be interested in initially, you wowould createjavax.activation.FileDataSourceInstance inDataHandler'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 your email.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.