Like the java.net classes, the JavaMail API can take advantage of an
Authenticator to access protected resources via a username and
password. For the JavaMail API, that resource is the mail server. The
JavaMail Authenticator is found in the javax.mail package and is
different from the java.net class of the same name. The two don't
share the same Authenticator as the JavaMail API works with Java 1.1,
which didn't have the java.net variety.
To use the Authenticator, you subclass the abstract class and return a
PasswordAuthentication instance from the getPasswordAuthentication()
method. You must register the Authenticator with the session when
created. Then, your Authenticator will be notified when authentication
is necessary. You could popup a window or read the username and
password from a configuration file (though if not encrypted it is not
secure), returning them to the caller as a PasswordAuthentication
object.
Properties props = new Properties();
// fill props with any information
Authenticator auth = new MyAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
Transport
The final part of sending a message is to use the Transport class.
This class speaks the protocol-specific language for sending the
message (usually SMTP). It's an abstract class and works something
like Session. You can use the default version of the class by just
calling the static send() method:
Transport.send(message);
Or, you can get a specific instance from the session for your
protocol, pass along the username and password (blank if unnecessary),
send the message, and close the connection:
message.saveChanges(); // implicit with send()
Transport transport = session.getTransport("smtp");
transport.connect(host, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
This latter way is best when you need to send multiple messages, as it
will keep the connection with the mail server active between messages.
The basic send() mechanism makes a separate connection to the server
for each method call.
--
www.zhouxinxin.com 王不留行
0 评论:
发表评论