This example describes how Java uses JavaMail to send mail. Share to everyone for your reference, specific as follows:
Code one, Email_autherticator.java server authentication code
Import Javax.mail.Authenticator;
Import javax.mail.PasswordAuthentication;
public class Email_autherticator extends Authenticator {
String username = "Username of your mailbox";
String password = "Password for your mailbox";
Public Email_autherticator () {
super ();
}
Public Email_autherticator (String user,string pwd) {
super ();
Username = user;
Password = pwd;
}
Public Passwordauthentication getpasswordauthentication () {return
new Passwordauthentication (username, password);
}
Code two, Mail.java code to send mail
Import Java.util.Date;
Import java.util.Properties;
Import javax.mail.Address;
Import Javax.mail.Authenticator;
Import Javax.mail.Message;
Import javax.mail.SendFailedException;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeMessage;
public class Mail {private String host = ' smtp.126.com ';
Private String Mail_head_name = "This are head to this mail";
Private String Mail_head_value = "This are head to this mail";
Private String mail_to = "254173774@qq.com";
Private String Mail_from = "hackboyo@126.com";
Private String Mail_subject = "This are the subject of this Test mail";
Private String Mail_body = "This is mail_body to this test mail";
Private String personalname = "my Mail"; public void SendMail () throws sendfailedexception{try {properties props = new properties ()//Get System Environment authenticator
Auth = new Email_autherticator ()//Mail Service user authentication Props.put ("Mail.smtp.host", host); Props. put ("Mail.smtp.auth", "true");
System.out.println (props);
Session session = Session.getdefaultinstance (Props,auth);
Set session, and mail server to communicate mimemessage message = new MimeMessage (session); Message.setcontent ("Hello", "Text/plain");//Set Message Format message.setsubject (mail_subject);/Set message theme message.settext (mail _body);/Set the message content Message.setheader (Mail_head_name, mail_head_value);//Set the message title Message.setsentdate (new Date ());/
Set the email send period address = new internetaddress (mail_from,personalname); Message.setfrom (address)//Set the Mail sender's addresses toaddress = new internetaddress (mail_to);/Set the address of the mail recipient Message.addrecip
Ient (message.recipienttype.to,toaddress);
SYSTEM.OUT.PRINTLN (message);
Transport.send (message);
System.out.println ("Send Mail ok!");
catch (Exception e) {e.printstacktrace ();
}//return Flag;
}
}
Code three, Test.java test the code to send the message
public class Test {public
static void Main (string[] args) {
mail m = new Mail ();
try {
m.sendmail ();
} catch (Exception e) {
}
}
}
I hope this article will help you with Java programming.