The implementation method of Java sending mail Javax.mail _java

Source: Internet
Author: User

Direct on Source:
1. The basic information of the message (easy to set to static)
It's best to be a JavaBean

 package com.lgf.Email; 
 
Import Java.util.Date; 
   public class Emailmessage {/** * message, you can set it yourself.   
* To facilitate direct all set to static///Recipient mailbox public static String to = "xxx@xxx.com";  
  Sender mailbox public static String from = "xxx@xxx.com";  
public static String from_name = "xxx";   
CC person public static String cc= "xxx@nxxx.com";     
Dark Send public static String bcc= "xxx@nxxx.com"; 
The type of the message is public static String email_content = "Text/plain";   
Message headers public static String Email_subject = "Test email with JavaMail";   
Message headers public static String Email_header = ' This is Email header ';  
Content public static String email_body = "<a href=\" http://www.baidu.com\ ">this is Email body</a>";      
Servers such as QQ can be set to smtp.qq.com public static String email_host = "smtp.xxx.com";  
Send time public static Date senddate = new Date ();    
Whether you need to verify the username and password public static Boolean validate = True; }

2. Server authentication (that is, the user name and password for the general login)

Package com.lgf.Email; 
 
Import Javax.mail.Authenticator; 
Import javax.mail.PasswordAuthentication; 
 
/** * 
 user name and password verification 
 * @author LGF * */Public 
class Mailauthenticator extends authenticator{ 
  Private String username= "xxxxx";   
  Private String password= "xxxxx";   
   
  Public Mailauthenticator () { 
    super (); 
  } 
   
  /** 
   * Set authenticated username and password/public 
  mailauthenticator (string userName, string password) { 
    super (); 
    This.username = Username; 
    This.password = password; 
  } 
  Protected Passwordauthentication getpasswordauthentication () 
  {return   
    new passwordauthentication ( This.username,this.password);   
  }   

3. Set up information and steps before sending a message

Package com.lgf.Email; 
 
Import java.util.Properties; 
Import Javax.activation.DataHandler; 
Import Javax.activation.DataSource; 
Import Javax.activation.FileDataSource; 
Import javax.mail.Address; 
Import Javax.mail.Authenticator; 
Import Javax.mail.BodyPart; 
Import Javax.mail.Message; 
Import Javax.mail.Multipart; 
Import javax.mail.Session; 
Import Javax.mail.Transport; 
Import javax.mail.internet.InternetAddress; 
Import Javax.mail.internet.MimeBodyPart; 
Import Javax.mail.internet.MimeMessage; 
 
Import Javax.mail.internet.MimeMultipart; 
 
Import Com.lgf.SendEmail.MailAuthenticator;  
  public class SendEmail {/** * send ordinary mail * @throws Exception/public void Dosendnormalmail ()  
    {//Get system Environment Properties prop = new properties (); 
Authenticator auth = null;  
    Determine if the send message needs to verify if (emailmessage.validate) {//mail server authenticated username and password auth = new Mailauthenticator (); //Add the necessary information Prop.put ("Mail.smtp.host", EmailmEssage.   
    Email_host);   
     
Prop.put ("Mail.smtp.auth", "true");   
Set up conversations and mail servers for communication session sessions = Session.getdefaultinstance (prop, auth); 
Displays the debug information Session.setdebug (TRUE) on the console;   
    Set Mail Object message = new MimeMessage (session);   
try {//Set the message subject Message.setsubject (Emailmessage.email_subject);  
Set the message header Message.setheader (header, Emailmessage.email_header); 
       
Set the sending time Message.setsentdate (emailmessage.senddate);   
Set the sender's address and name addresses = new InternetAddress (Emailmessage.from, emailmessage.from_name);   
       
Add the sender information to the information Message.setfrom (address);  
Set the sender address toaddress = new internetaddress (emailmessage.to);   
      
Set the recipient address Message.setrecipient (Message.RecipientType.TO, toaddress);   
 
Set up multiple recipient addresses//Message.addrecipient (message.recipienttype.to,new internetaddress ("xxx@xxx.com")); Set upMessage Format message.setcontent ("Content", emailmessage.email_content);  
       
Setting the message content must be Message.settext (emailmessage.email_body) after the file format is set;   
Save the information added above Message.savechanges ();   
      Send mail System.out.println ("Sendnormalemail () Start sending mail ...");   
      Transport.send (message); SYSTEM.OUT.PRINTLN ("Send success!")   
    ");   
        catch (Exception e) {System.out.println ("error");   
    E.printstacktrace ();  }/** * Send HTML message/public void Dosendhtmlmail () {//Get system Environment Properties prop  
 
    = new Properties (); 
    Authenticator auth = null; 
    if (emailmessage.validate) {//mail server authenticated username and password auth = new Mailauthenticator ();   
    //Add the necessary information Prop.put ("Mail.smtp.host", emailmessage.email_host);   
     
Prop.put ("Mail.smtp.auth", "true");   
     
Set up conversations and mail servers for communication session sessions = Session.getdefaultinstance (prop, auth); Set Mail Object Message MessaGE = new MimeMessage (session);   
try {//Set the message subject Message.setsubject (Emailmessage.email_subject);  
Set the message header Message.setheader (header, Emailmessage.email_header); 
       
Set the sending time Message.setsentdate (emailmessage.senddate);   
Set the sender's address and name addresses = new InternetAddress (Emailmessage.from, emailmessage.from_name);   
       
Add the sender information to the information Message.setfrom (address);  
Set the sender address toaddress = new internetaddress (emailmessage.to);   
      
Set the recipient address Message.setrecipient (Message.RecipientType.TO, toaddress);   
 
Set up multiple recipient addresses//Message.addrecipient (message.recipienttype.to,new internetaddress ("xxx@xxx.com")); Set the content to send the message below for sending HMML//setting mail format emailmessage.email_content = "text/html;" 
      Charset=utf-8 ";  
 
Message.setcontent (Emailmessage.email_body, emailmessage.email_content);   
Save the information added above Message.savechanges ();     // Send mail System.out.println ("Dosendhtmlmail () Start sending mail ...");   
      Transport.send (message); SYSTEM.OUT.PRINTLN ("Send success!")   
    ");   
        catch (Exception e) {System.out.println ("error");   
    E.printstacktrace (); }/** * Send mail with attached format */public void Dosendattachmentmail () {//Get system Environment Properties PR  
 
    op = new Properties (); 
    Authenticator auth = null; 
    if (emailmessage.validate) {//mail server authenticated username and password auth = new Mailauthenticator ();   
    //Add the necessary information Prop.put ("Mail.smtp.host", emailmessage.email_host);   
     
Prop.put ("Mail.smtp.auth", "true");   
     
Set up conversations and mail servers for communication session sessions = Session.getdefaultinstance (prop, auth);   
    Set Mail Object message = new MimeMessage (session);   
try {//Set the message subject Message.setsubject (Emailmessage.email_subject);  
Set the message header Message.setheader (header, Emailmessage.email_header);     // Set the sending time Message.setsentdate (emailmessage.senddate);   
Set the sender's address and name addresses = new InternetAddress (Emailmessage.from, emailmessage.from_name);   
       
Add the sender information to the information Message.setfrom (address);  
Set the sender address toaddress = new internetaddress (emailmessage.to);   
      
Set the recipient address Message.setrecipient (Message.RecipientType.TO, toaddress);   
      
       
Set up multiple recipient addresses//Message.addrecipient (message.recipienttype.to,new internetaddress ("xxx@xxx.com"));  
       
      Set the content to send the message below for sending the attachment message.setcontent (Emailmessage.email_body, emailmessage.email_content);   
      BodyPart Messagebodypart = new MimeBodyPart ();   
       
      Messagebodypart.settext ("BodyPart");   
      Multipart Multipart = new Mimemultipart ();   
       
      Multipart.addbodypart (Messagebodypart);   
       
Messagebodypart = new MimeBodyPart (); Set the uploaded resource DataSource Source = new Filedatasource ("E:\\3.doc");   
Add to Messagebodypart.setdatahandler (new DataHandler (source));   
      Set file name, remember suffix name messagebodypart.setfilename ("Test.doc");  
       
      Multipart.addbodypart (Messagebodypart);   
       
Message.setcontent (multipart);   
Save the information added above Message.savechanges ();   
      Send mail System.out.println ("Dosendattachmentmail () Start sending mail ...");   
      Transport.send (message); SYSTEM.OUT.PRINTLN ("Send success!")   
    ");   
        catch (Exception e) {System.out.println ("error");   
    E.printstacktrace (); }/** * @param args */public static void main (string[] args) {//New SendEmail (). Dosendnorm 
Almail (); 
    New SendEmail (). Dosendhtmlmail (); 
  New SendEmail (). Dosendattachmentmail ();  } 
 
}

Above is the Java sends the mail javax.mail the detailed code, hoped that can realize the Java Mail sends to have the help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.