Java code example for sending and receiving mail using the JavaMail API _java

Source: Internet
Author: User
Tags auth int size mixed ssh ssh config

Use JavaMail to send mail, required jar packs (please download JavaMail source file, official download page: http://www.oracle.com/technetwork/java/javamail/index-138643.html):
Mailapi.jar. Defines the interface API used to send and receive messages;
Smtp.jar. Contains the class used to send the message;
Pop3.jar. Contains the class used to receive mail;
The protocol that we normally use to send mail is the SMTP protocol, and the protocol used to accept mail is the POP3 protocol. Alternatively, we add Mail.jar directly to the project, which contains all the interfaces and classes for the Java transceiver.

Common classes:

  • Javax.mail.Session; --------> Save the information required to connect to the server;
  • Javax.mail.Message; --------> Mail body, save the content of the message;
  • Javax.mail.Transport; --------> carrier for sending mail
  • javax.mail.internet.InternetAddress; Address information for--------> mail

Send mail

Below, I first list the simplest example of a small test that uses Java to send mail:

Import java.util.Properties; 
Import javax.mail.Address; 
Import Javax.mail.Message; 
Import javax.mail.MessagingException; 
Import javax.mail.Session; 
Import Javax.mail.Transport; 
Import javax.mail.internet.InternetAddress; 
 
Import Javax.mail.internet.MimeMessage; 
 /** * * QQ (mail.qq.com):P OP3 Server (port 995) SMTP server (port 465 or 587). * */public class Demo1 {/** * @param args * @throws messagingexception/public static void main 
    (string[] args) throws Messagingexception {String sendusername = "wangxiangpan@126.com"; 
     
    String Sendpassword = "pwd"; 
    Properties Properties = new properties (); Properties.setproperty ("Mail.smtp.auth", "true");/server requires authentication Properties.setproperty ("Mail.transport.protocol", " 
    SMTP ")//declares the port used to send the message session session = Session.getinstance (properties); Session.setdebug (TRUE);/agree to print on the console of the current thread with server dialog information message = new MimeMessage (session);//build Sent information Messag E.settext ("Hello, this is champi.On. wong! //Information Content Message.setfrom (new internetaddress ("wangxiangpan@126.com"))//Sender Transport Transport = Session 
    . Gettransport (); Transport.connect ("smtp.126.com", "Sendusername, Sendpassword")//Connect the sender using the sender's server transport.sendmessage (message, 
  New Address[]{new internetaddress ("492134880@qq.com")});//Accept Mail transport.close (); 
 } 
 
}

Generally, we use authenticator to encapsulate username and password, opaque! So:

Import Javax.mail.Authenticator; 
Import Javax.mail.Message; 
Import javax.mail.MessagingException; 
Import javax.mail.PasswordAuthentication; 
Import javax.mail.Session; 
Import Javax.mail.Transport; 
Import javax.mail.internet.AddressException; 
Import javax.mail.internet.InternetAddress; 
 
Import Javax.mail.internet.MimeMessage; 
 
Import Junit.framework.TestCase; /** * javamail Send mail * @author Champion Wong * message.addrecipient (message.recipient recipient, address); When you send an email, specify the recipient and recipient's role * Message.RecipientType.TO recipient * Message.RecipientType.CC cc, that is, the time to send a message to another person to copy, do not reply!  However, the recipient can see that you have been copied to the * Message.RecipientType.BCC dark send, but also send a message when the other person secretly sent a, but, unlike the above is, the recipient can not see you have been secretly sent to the * * * * * * public class 
 
  Demo2 extends TestCase {private static final String Sendusername = "wangxiangpan@126.com";/the user name of the server to which the message needs to be connected private static final String Sendpassword = "pwd";/the password of the server to which the message needs to be connected private static final string sendprotocol = "SMTP" ;//Send mail using the port private staticFinal String sendhostaddress = "smtp.126.com";/the address of the server used to send the message is public void test () throws Addressexception, Messaginge 
    Xception {Properties Properties = new properties (); Properties.setproperty ("Mail.smtp.auth", "true");/server requires authentication Properties.setproperty ("Mail.transport.protocol", SENDPROTOCOL)//declares the port used to send the message Properties.setproperty ("Mail.host", sendhostaddress), or the server address for sending the message session Sessio n = Session.getinstance (properties, new Authenticator () {protected passwordauthentication Getpasswordauthenticatio 
      N () {return new passwordauthentication (Sendusername, Sendpassword); 
    } 
    }); 
    Session.setdebug (TRUE);//In the background print the real-time message of the message = new MimeMessage (session); 
    Message.setfrom (New InternetAddress ("wangxiangpan@126.com")); Message.setsubject ("Demo2javacode send mail test, use authenticator");/set Theme Message.setrecipients (Message.RecipientType.TO , InternetAddress Parse ("492134880@qq.com,wangxiangpan@126.com"))//Send Message.setrecipients (Message.RecipientType.CC, internetaddress. Parse ("msn_wangxiangpan@hotmail.co m);/CC message. SetContent ("<span style=" font-size:20px; color: #FFCCFF "mce_style=" font -size:20px; Color: #FFCCFF "> If you see, prove the test is successful!" 
 
    </span> "," TEXT/HTML;CHARSET=GBK "); 
 Transport.send (message);//Send Mail}}

We send a more complex message, including attachments, graphics and text:

Import java.io.FileNotFoundException; 
Import Java.io.FileOutputStream; 
Import java.io.IOException; 
Import Java.io.OutputStream; 
 
Import java.util.Properties; 
Import Javax.activation.DataHandler; 
Import Javax.activation.DataSource; 
Import Javax.activation.FileDataSource; 
Import Javax.mail.Authenticator; 
Import javax.mail.MessagingException; 
Import javax.mail.PasswordAuthentication; 
Import javax.mail.Session; 
Import Javax.mail.Transport; 
Import Javax.mail.Message.RecipientType; 
Import javax.mail.internet.InternetAddress; 
Import Javax.mail.internet.MimeBodyPart; 
Import Javax.mail.internet.MimeMessage; 
Import Javax.mail.internet.MimeMultipart; 
 
Import javax.mail.internet.MimeUtility; /** * * @author Administrator Mr XP.  Wang * Mimemultipart the container for general e-mail is multipart, which defines ways to add and remove portions of an e-mail message, but it is an abstract class that requires its subclass Mimemultipart to be mimemessage object * MimeBodyPart is a subclass of BodyPart specifically for MimeMessage, MimeBodyPart objects represent each part of a * Mimemultipart Object * Mimeutility.encodetext ( StrinG cn) is used to solve the header information in the message in Chinese garbled problem * * */public class Demo3_test {public static void main (string[] args) throws Exception 
    {Properties Properties = new properties (); Properties.setproperty ("Mail.smtp.auth", "true");/server requires authentication Properties.setproperty ("Mail.transport.protocol", " SMTP ")//declares the port Properties.setproperty (" Mail.host "," smtp.126.com ") used to send the message; 
      Session.getinstance (Properties, new Authenticator () {String sendusername = "wangxiangpan@126.com"; 
      String Sendpassword = "pwd"; 
            Protected Passwordauthentication getpasswordauthentication () {Return to New Passwordauthentication (Sendusername, 
      Sendpassword); 
    } 
    }); 
     
    Session.setdebug (TRUE);  MimeMessage msg = new MimeMessage (session)//Declare a message body msg.setfrom (new internetaddress ("/" +mimeutility.encodetext ("Mr WPA 
    Wang ") +"/"<wangxiangpan@126.com>"); Msg.setsubject ("This is my first complex mail");/set the message subject MSG.SEtrecipients (MimeMessage.RecipientType.TO, Internetaddress.parse (Mimeutility.encodetext ("Xiang Wang Climb") + "< 
 
    Wangxiangpan@126.com>, "+mimeutility.encodetext (" Sanmao ") +" <492134880@qq.com> ")); 
     
 
    Mimemultipart Msgmultipart = new Mimemultipart ("mixed");//Indicates the composition of the message, mixed relationship msg.setcontent (Msgmultipart);/Set the message body MimeBodyPart attch1 = new MimeBodyPart ()//Annex 1 MimeBodyPart ATTCH2 = new MimeBodyPart ();//Annex 2 Mimebod 
    Ypart content = new MimeBodyPart ()//The body of the message, the mixture (picture + text)//Set the attachment and body to the body of the message Msgmultipart.addbodypart (ATTCH1); 
    Msgmultipart.addbodypart (ATTCH2); 
     
 
    Msgmultipart.addbodypart (content); Sets the first attachment DataSource DS1 = new Filedatasource ("f:/accp5.0/file/ssh config. txt");//Specify the data source for the attachment datahandler DH1 = new 
 
    Handler (DS1);//Attachment Information Attch1.setdatahandler (DH1);//Designated Accessory Attch1.setfilename ("ssh.txt"); Sets the second attachment DataSource DS2 = new Filedatasource ("resource/48.jpg");//Specifies the data source for the attachment DataHandler DH2 = new DataHandler ( Ds2)//Attachment information Attch2.setdatahandler (DH2);//Specify Attachment Attch2.setfilename ("48.jpg"); Set the body of the message mimemultipart Bodymultipart = new Mimemultipart ("related");//Dependency content.setcontent (Bodymultipart); 
    Specifies the body mimebodypart htmlpart = new MimeBodyPart (); 
    MimeBodyPart Gifpart = new MimeBodyPart (); 
    Bodymultipart.addbodypart (Htmlpart); 
     
     
    Bodymultipart.addbodypart (Gifpart); 
    DataSource Gifds = new Filedatasource ("resource/48.jpg");//The Body of the picture datahandler GIFDH = new DataHandler (GIFDS); 
    Gifpart.setheader ("Content-location", "yun_qi_img/126logo.gif"); Gifpart.setdatahandler (GIFDH)//Set the text of the picture htmlpart.setcontent ("I just come to soy sauce, this is my image photo!"  "," TEXT/HTML;CHARSET=GBK ");/Set body text Msg. SaveChanges ()//Save message//save mail as file OutputStream Ops = new FileOutputStream ("C:/users/administrator/desktop/te 
    St.eml "); 
    Msg.writeto (OPS); 
     
  Ops.close ();  Transport.send (msg); 
 } 
 
}

receive mail
Example: Rose collects the most recent e-mail message.

Import Java.util.Date;
Import java.util.Properties;
Import Javax.mail.Folder;
Import Javax.mail.Message;
Import javax.mail.MessagingException;
Import javax.mail.NoSuchProviderException;
Import javax.mail.Session;

Import Javax.mail.Store;
    public class FetchMail {public static void main (string[] args) {String protocol = "POP3";
    Boolean Isssl = true;
    String host = "pop.163.com";
    int port = 995;
    String username = "rose@163.com";

    String password = "Rose";
    Properties Props = new properties ();
    Props.put ("mail.pop3.ssl.enable", Isssl);
    Props.put ("Mail.pop3.host", host);

    Props.put ("Mail.pop3.port", port);

    Session session = Session.getdefaultinstance (props);
    Store store = null;
    Folder folder = null;
      try {store = session.getstore (protocol);

      Store.connect (username, password);
      folder = Store.getfolder ("INBOX");

      Folder.open (folder.read_only);
      int size = Folder.getmessagecount (); Message message = Folder.getmessage (size);
      String from = Message.getfrom () [0].tostring ();
      String subject = Message.getsubject ();

      Date date = Message.getsentdate ();
      System.out.println ("From:" + from);
      System.out.println ("Subject:" + Subject);
    System.out.println ("Date:" + date);
    catch (Nosuchproviderexception e) {e.printstacktrace ();
    catch (Messagingexception e) {e.printstacktrace ();
        Finally {try {if (folder!= null) {Folder.close (false);
        } if (store!= null) {store.close ();
      } catch (Messagingexception e) {e.printstacktrace (); } System.out.println ("Receive complete!")
  ");
 }
}

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.