The following sections describe how to send and read messages using the JavaMail API:
Import the packages that you need.
import java.util.*; import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; import javax.naming.*;
Look up the JavaMail session.
InitialContext ic = new InitialContext(); String snName = "java:comp/env/mail/MyMailSession"; Session session = (Session)ic.lookup(snName);
For more information, see Looking Up a JavaMail Session.
Override the JavaMail session properties if necessary.
For example:
Properties props = session.getProperties(); props.put("mail.from", "user2@mailserver.com");
Create a MimeMessage.
The msgRecipient, msgSubject, and msgTxt variables in the following example contain input from the user:
Message msg = new MimeMessage(session); msg.setSubject(msgSubject); msg.setSentDate(new Date()); msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(msgRecipient, false)); msg.setText(msgTxt);
Send the message.
Transport.send(msg);
Import the packages that you need.
import java.util.*; import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; import javax.naming.*;
Look up the JavaMail session.
InitialContext ic = new InitialContext(); String snName = "java:comp/env/mail/MyMailSession"; Session session = (javax.mail.Session)ic.lookup(snName);
For more information, see Looking Up a JavaMail Session.
Override the JavaMail session properties if necessary.
For example:
Properties props = session.getProperties(); props.put("mail.from", "user2@mailserver.com");
Get a Store object from the Session, then connect to the mail server using the Store object’s connect() method.
You must supply a mail server name, a mail user name, and a password.
Store store = session.getStore(); store.connect("MailServer", "MailUser", "secret");
Get the INBOX folder.
Folder folder = store.getFolder("INBOX");
It is efficient to read the Message objects (which represent messages on the server) into an array.
Message[] messages = folder.getMessages();