[Html]
Package test;
Import java. util. Date;
Import java. util. Properties;
Import javax. mail. Address;
Import javax. mail. Authenticator;
Import javax. mail. Message;
Import javax. mail. PasswordAuthentication;
Import javax. mail. Session;
Import javax. mail. Transport;
Import javax. mail. internet. InternetAddress;
Import javax. mail. internet. MimeMessage;
/**
* Send a common email, send an email with an attachment to a common email, and receive an html-based email from an email with an attachment, the following is a summary of emails with images sent in html format.
*/
Public class SendMail {
// Email server
Private String host = "smtp.163.com ";
// This is your email user name
Private String username = "****** @ 163.com ";
// Your email password
Private String password = "******";
Private String mail_head_name = "mail title ";
Private String mail_head_value = "mail title ";
Private String mail_to = "****** @ qq.com ";
Private String mail_from = "****** @ 163.com ";
Private String mail_subject = "mail title ";
Private String mail_body = "email content ";
Private String personalName = "JavaMail send mail test ";
/**
* This code is used to send a common email.
*/
Public void send () throws Exception {
Try {
Properties props = new Properties (); // obtain the system environment
Authenticator auth = new Email_Autherticator (); // Authenticator
Props. put ("mail. smtp. host", host );
Props. put ("mail. smtp. auth", "true ");
Session session = Session. getDefaultInstance (props, auth );
// Set the session to communicate with the email server.
MimeMessage message = new MimeMessage (session );
// Message. setContent ("foobar," application/x-foobar "); // you can specify the mail format.
Message. setSubject (mail_subject); // you can specify a subject.
Message. setText (mail_body); // you can specify the mail body.
Message. setHeader (mail_head_name, mail_head_value); // you can specify the mail title.
Message. setSentDate (new Date (); // you can specify the mail sending Date.
Address address = new InternetAddress (mail_from, personalName );
Message. setFrom (address); // you can specify the sender's address.
Address toAddress = new InternetAddress (mail_to); // you can specify the email receiver Address.
Message. addRecipient (Message. RecipientType. TO, toAddress );
Transport. send (message); // send an email
System. out. println ("send OK! ");
} Catch (Exception ex ){
Ex. printStackTrace ();
Throw new Exception (ex. getMessage ());
}
}
/**
* Used for server-to-user authentication
*/
Public class Email_Autherticator extends Authenticator {
Public Email_Autherticator (){
Super ();
}
Public Email_Autherticator (String user, String pwd ){
Super ();
Username = user;
Password = pwd;
}
Public PasswordAuthentication getPasswordAuthentication (){
Return new PasswordAuthentication (username, password );
}
}
Public static void main (String [] args ){
SendMail sendmail = new SendMail ();
Try {
Sendmail. send ();
} Catch (Exception ex ){
}
}
}