The JavaMail API allows Java applications to send and receive email. It includes core classes like Session, Message, Transport, and Store. A Session represents a mail session with an email server. Messages can be composed and sent using Transport, and email can be retrieved from mailboxes using Store and Folder classes. The API supports authentication, sending attachments, and receiving notifications about mail events.
2. JavaMail Setup
Add JAR files
mail.jar and activation.jar to CLASSPATH, to
jre/lib/ext
Included with Java 2 platform, Enterprise Edition
3. Core Classes
Session
Message / MimeMessage
InternetAddress
Authenticator
Transport
Store
4. Session
Represents a mail session with server
Uses Properties to get things like mail host
mail.transport.default
mail.smtp.host
Get session - no constructor
Properties props = new Properties();
props.put(“mail.transport.default”, “smtp”);
props.put(“mail.smtp.host”, “mail.cs.wmich.edu”);
Session session = Session.getInstance(props, null); // null for Authenticator
Session session = Session.getDefaultInstance(props, null);
5. Message / MimeMessage
Represents a mail message
Message abstract class
implements Part
MimeMessage is MIME style email message
implements MimePart
Get message from session
MimeMessage message = new MimeMessage(session);
Set parts
message.setContent() / mimeMessage.setText()
6. InternetAddress
RFC822 Address
Create:
new InternetAddress(“BillSomebody@wmich.edu");
new InternetAddress(“BillSomebody@wmich.edu ",
“Bill Someone");
For To, From, CC, BCC
message.setFrom(address)
message.addRecipient(type, address)
Types
Message.RecipientType.TO
Message.RecipientType.CC
Message.RecipientType.BCC
7. Authenticator
Permit mechanism to prompt for username and
password
javax.mail.Authenticator != java.net.Authenticator
Extend Authenticator
Override:
public PasswordAuthentication getPasswordAuthentication()
{
String username, password; // Then get them ...
return new PasswordAuthentication(username, password);
}
8. Transport
Message transport mechanism
Get transport for session
Transport transport = session.getTransport("smtp");
Connect
transport.connect(host, username, password);
Act - repeat if necessary
transport.sendMessage(message,
message.getAllRecipients());
Done
transport.close();
9. Sending Mail
Need a working SMTP server
Can be written in Java using JavaMail
API need from/to addresses, but don’t
need to be valid, unless SMTP server
includes some form of verification
10. Sending Mail
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class MailExample {
public static void main (String args[]) throws Exception {
String host = args[0];
String from = args[1];
String to = args[2];
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);
11. Sending Mail (contd.)
// Get session
Session session = Session.getInstance(props, null);
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(“Test E-mail");
message.setText(“Hello World!");
// Send message
Transport.send(message);
}
}
12. Getting Mail
There are mailbox store providers
available (POP3 and IMAP).
13. Getting Mail
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class GetMessageExample {
public static void main (String args[]) throws Exception {
String host = args[0];
String username = args[1];
String password = args[2];
// Create empty properties
Properties props = new Properties();
// Get session
Session session = Session.getInstance(props, null);
14. Getting Mail (contd.)
// Get the store
Store store = session.getStore("pop3");
store.connect(host, username, password);
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
BufferedReader reader = new BufferedReader (
new InputStreamReader(System.in));
// Get directory
Message message[] = folder.getMessages();
for (int i=0, n=message.length; i<n; i++) {
15. Getting Mail (contd.)
System.out.println(i + ": " + message[i].getFrom()[0]
+ "t" + message[i].getSubject());
System.out.println("Do you want to read message? [YES to
read/QUIT to end]");
String line = reader.readLine();
if ("YES".equals(line)) {
message[i].writeTo(System.out);
} else if ("QUIT".equals(line)) {
break;
}
}
// Close connection
folder.close(false);
store.close();
}
}
16. Authenticator Usage
Put host in properties
Properties props = new Properties();
props.put("mail.host", host);
Setup authentication, get session
Authenticator auth = new PopupAuthenticator();
Session session = Session.getInstance(props, auth);
Get the store
Store store = session.getStore("pop3");
store.connect();
17. Sending Attachments
Each attachment goes
into a MimeBodyPart
DataHandler deals with
reading in contents
Provide it with a
URLDataSource or
FileDataSource.
18. Sending Attachments
// create mime message object and set the required parameters
MimeMessage message = createMessage(to, cc, subject);
// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
//fill message
messageBodyPart.setText(msg);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// fill the array of files to be attached
File [] attachments = { .... }
19. Sending Attachments (Contd.)
for( int i = 0; i < attachments.length; i++ ) {
messageBodyPart = new MimeBodyPart();
FileDataSource fileDataSource =new FileDataSource(attachments[i]);
messageBodyPart.setDataHandler(new DataHandler(fileDataSource));
messageBodyPart.setFileName(attachments[i].getName());
multipart.addBodyPart(messageBodyPart);
}
// add the Multipart to the message
message.setContent(multipart);
// SEND THE MESSAGE
Transport.send(message);
20. Notification Events
Transport/Store/Folder.addConnectionListener()
open, closed, disconnected
Folder.addFolderListener()
created, deleted, renamed
Folder.addMessageCountListener()
Find out when new messages are received
Folder.addMessageChangeListener
changed
Store.addStoreListener
notification
Transport.addTransportListener
message delivered, not delivered, partially delivered