- First, get the Session object:
Properties props = new Properties();
// From system properties
//Properties props = System.getProperties();
// Get the shared Session object
Session session = Session.getDefaultInstance(props);
// Get an unshared Session object
Session session = Session.getInstance(props);The "props" Properties file contains mail protocols to use, mail host and port to connect to, username etc. which will be used later to connect to the mail server. It can be blank although you may want to set
mail.store.protocol
,mail.transport.protocol
,mail.host
,mail.user
andmail.from
properties. Passwords can not be specified using properties. Here are the various properties that can be in the Properties object and what they do:- mail.store.protocol: Default protocol to fetch messages.
- mail.transport.protocol: Default protocol to send messages.
- mail.protocol.host: Protocol-specific default mail server such as
mail.smtp.host=smtp2.yourisp.com
. Defaults to what's in "mail.host" property (see next). - mail.host: Default mail server for both sending and receiving email.
- mail.user: Mail server username. Defaults to the JVM system property
user.name
. The Store and Transport objects' connect() method uses this property to send the username to the mail server, if the protocol-specific username property is absent (see next). - mail.protocol.user: Protocol-specific default username for connecting to the mail server. Defaults to what's in "mail.user" property.
- mail.from: Specifies the return address of the current user. Used by the
InternetAddress.getLocalAddress
method to specify the current user's email address. Defaults tousername@host
. - mail.debug: If specified as "true" string, prints messages to System.out showing various protocol commands being issued behind the scenes. Default is "false". You can override it later with "Session.setDebug" method but then, debug messages will only be turned on from that point onwards and you will miss the session creation messages.
Sending E-Mail
- Instantiate a new message:
Message msg = new MimeMessage(session);
- Set message's attributes:
InternetAddress[] toAddrs = new InternetAddress[1];
toAddrs[0] = new InternetAddress("your@buddy.com");
Address fromAddr = new InternetAddress("you@home.com");
msg.setFrom(fromAddr);
msg.setRecipients(Message.RecipientType.TO, toAddrs);
msg.setSubject("Test Email");
msg.setSentDate(new Date());
// Custom header other than pre-defined ones
msg.setHeader("content-type", "text/plain"); - Set message's content:
msg.setText("This is a test message");
// Or, for other content types, e.g.
msg.setContent("This is a test message", "text/plain");- To create MIME multipart content, first instantiate a
MimeMultipart
object. The default subtype of a multipart content is "mixed". You can specify other subtypes such as "alternative", "related", "parallel" and "signed".Multipart mp = new MimeMultipart();
// Some other subtype
//Multipart mp = new MimeMultipart("alternative"); - Instantiate and set content of
MimeBodyPart
objectsBodyPart b1 = new MimeBodyPart();
b1.setContent("Spaceport Map","text/plain");
BodyPart b2 = new MimeBodyPart();
// Map is some binary postscript file
b2.setContent(map,"application/postscript"); - Add
BodyPart
objects toMultipart
objectmp.addBodyPart(b1);
mp.addBodyPart(b2); - Finally, set the
Multipart
object as the message's contentmsg.setContent(mp); // This form takes a Multipart object
- To create MIME multipart content, first instantiate a
- Send the message
- Automatic Procedure:
Transport.send(msg);
// Ignore recipient addresses in the Message object, specify your own
Transport.send(msg, recipientAddressesArray);This is a convenience static method. It does not allow registering event listeners with the Transport object. Depending on each recipient's address type, it instantiates the appropriate Transport subclass, calls
msg.saveChanges()
and callstransportObject.sendMessage(msg)
. - Manual Procedure:
- Ensure that proper message headers are updated:
msg.saveChanges();
- Get a Transport object specific to the send protocol (usually "smtp")
// Use provider configuration file
Transport bus = session.getTransport("smtp");
// Use address type to protocol mapping file
//Transport bus = session.getTransport(address);
// Use session properties to get default protocol
//Transport bus = session.getTransport(); - Register event listeners if you want:
// Add a class implementing the appropriate listener interface
bus.addConnectionListener(this); // this implements ConnectionListener
bus.addTransportListener(this); // this implements TransportListener - Make recipient address array:
Address [] addresses = msg.getAllRecipients();
// Or, Make your own
Address [] addresses = {
new InternetAddress("you@me.com"),
new InternetAddress("me@you.com"),
}; - Send the message:
bus.sendMessage(msg, addresses);
- Ensure that proper message headers are updated:
- Automatic Procedure:
- Optionally, write the message out to a bytestream (may be to save as a draft on disk, for example):
msg.writeTo(someOutputStream);
- Instantiate a new message:
Fetching E-Mail
- Get the Store object:
// Gets protocol from session properties
Store store = session.getStore();
// Store for a non-default protocol
Store store = session.getStore("pop3"); - Connect to the store:
//Uses session properties
store.connect();
//uses default port, hostString is like "mail.yourisp.com"
store.connect(hostString, username, password);
//uses specific port, -1 means default
store.connect(hostString, portNumberInteger username, password); - List folders in the store and list/view messages in a folder:
// get the INBOX folder (All stores usually have this one)
Folder inbox = store.getFolder("INBOX");
// open the INBOX folder
inbox.open(Folder.READ_WRITE);
Message m = inbox.getMessage(1); // get Message #1 - Get a message's attributes:
// Get the subject attribute
String subject = m.getSubject(); - Return the MIME type of a message's content:
String mimeType = m.getContentType();
- Get a message's content:
Object o = m.getContent();
- The type of the returned object depends on the type of the actual content.
- A "text/plain" content usually returns a String object.
- A "multipart/%lt;whatever here>" object always returns a
Multipart
object or its subclass. - For unknown content types, any mail-specific encodings are decoded and an
InputStream
object is returned.
if (o instanceof String) {
System.out.println("This is a String");
System.out.println((String)o);
}
else if (o instanceof Multipart) {
System.out.println("This is a Multipart");
Multipart mp = (Multipart)o;
int count = mp.getCount();
for (int i = 0; i < count; i++) {
BodyPart b = mp.getBodyPart(i);
mp.removeBodyPart(b);
// Or, simply
//mp.removeBodyPart(i);
mp.addBodyPart(b);
}
}
else if (o instanceof InputStream) {
System.out.println("This is just an input stream");
InputStream is = (InputStream)o;
int c;
while ((c = is.read()) != -1) {
System.out.write(c);
}
} - When done, close all open folders and then, the store:
inbox.close(); // Close the INBOX
store.close(); // Close the Store
- Get the Store object:
Thursday, July 15, 2010
Steps to Use JavaMail
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment