This article describes how to use javamail to send HTML-format emails through the SMTP server to be authenticated.
First, download the implementation of javamail on the sun website, and add your classpath to the implementation of JAF (I don't know why I don't want to put it together.
The code first inherits a class from authenticator, such as smtpauthenticator, which is used for authentication when connecting to the SMTP server.
Class smtpauthenticator extends authenticator {
Private string user;
Private string password;
Public smtpauthenticator (string S, string S1 ){
User = s;
Password = S1;
}
Public passwordauthentication getpasswordauthentication (){
Return new passwordauthentication (user, password );
}
}
Then start sending emails,
Session sendmailsession = NULL;
Smtptransport transport = NULL;
Properties props = new properties ();
// Set the parameters for setting the session with the server
Props. Put ("mail. SMTP. Host", "smtp.163.com"); // write your SMTP server.
Props. Put ("mail. SMTP. Auth", "true"); // set this parameter to true for server authentication.
Smtpauthenticator auth = new smtpauthenticator ("user", "mypassword"); // needless to say, user name, password.
Sendmailsession = session. getinstance (props, auth); // establish a connection.
// Smtptransport is used to send emails.
Transport = (smtptransport) sendmailsession. gettransport ("SMTP ");
Transport. Connect ();
// Create an email.
Message newmessage = new mimemessage (sendmailsession );
Newmessage. setfrom (New internetaddress ("me@163.com "));
Newmessage. setrecipient (message. recipienttype. To, new internetaddress ("somebody@gmail.com "));
Newmessage. setsubject ("this a test mail for Java mail API );
Newmessage. setsentdate (new date ());
// Use mimemultipart and mimebodypart to send HTML-formatted emails.
Bodypart = new mimebodypart ();
Bodypart. setcontent (generateemailbody (), "text/html; charset = gb2312"); // send an html
Multipart MP = new mimemultipart ();
MP. addbodypart (bodypart );
Newmessage. setcontent (MP );
Transport. Send (newmessage );
OK. The email is sent ~~