Reprint Please specify source: http://blog.csdn.net/qq_26525215
This article is from the "university trip _ Remember the blog"
JAVAMAIL-API Introduction:
The primary task for the mail client is to send mail to the mail server and receive messages from the mail server.
Sun has developed a set of APIs that encapsulate the various protocols for mail communication. Provides a common interface for Java developers to send and receive e-mail.
Required JAR Package
Mail.jar and Activation-1.1.0.jar Links:
Https://github.com/chenhaoxiang/Java/tree/master/JavaMail
Javax.mail.Session:
Session-Used to set the server, protocol type and password, etc.
Represents a session, which is the top-level entry class for JAVAMAILAPI. Session to get information like from properties, such as IP, protocol, username password, etc.
The Javax.mail.Message class, an important subclass of which is mimemessage.
The message class represents the body part of an e-mail message.
An e-mail message contains the following content:
Address information, title, date, body.
Java.mail.Address: Recipient Address
Represents the address of the message. The commonly used subclasses are: javax.mail.internet.InternetAddress.
Javax.mail.Transport: responsible for sending mail
Specifies the protocol that the message is sent. This is usually SMTP.
Its static method send (message) is responsible for sending the message.
Mailsslsocketfactory-is responsible for SSL encryption (if there is a mailbox is encrypted with SSL transmission, you need to use this class, otherwise do not need-the old version of the jar package does not have this type)
Demo QQ email to 126 e-mail:
Why use QQ mailbox, that is because QQ mailbox sent with SSL encryption, and here originally need the password, also need to use authorization code can.
JavaMail Send mail: The premise is QQ mailbox account set to open POP3/SMTP protocol
Send messages without attachments the first way:
@Test//Send mail with no attachments Public void Send1()throwsexception{//Establish a connection with the SMTP serverProperties p =NewProperties ();//Set mail server host nameP.setproperty ("Mail.host","Smtp.qq.com");//Specify mail server, default port //The Sending server needs authenticationP.setproperty ("Mail.smtp.auth","true");//To authenticate with the specified user name password //Send mail Agreement nameP.setproperty ("Mail.transport.protocol","SMTP");//Turn on SSL encryption, or it will failMailsslsocketfactory SF =NewMailsslsocketfactory (); Sf.settrustallhosts (true); P.put ("Mail.smtp.ssl.enable","true"); P.put ("Mail.smtp.ssl.socketFactory", SF);//Turn on debug debugging for viewing in the console //session.setdebug (TRUE); You can also set this //p.setproperty ("Mail.debug", "true"); //Create sessionSession session = Session.getdefaultinstance (p,NewAuthenticator () {@Override protectedPasswordauthenticationgetpasswordauthentication() {//user name can use QQ account can also use the alias of the mailboxPasswordauthentication PA =NewPasswordauthentication ("chenhaoxiang0117","Jnj*********dab");//After the character is the authorization code, with the QQ password does not!! returnPa } }); Session.setdebug (true);//Set open debug State for(inti =0; I <1; i++) {//Send several emails //Declare a Message object (representing a message) and create it from the sessionMimeMessage msg =NewMimeMessage (session);//Mail message Encapsulation //1 SenderMsg.setfrom (NewInternetAddress ("* * * * * @qq. com"));//2 RecipientsMsg.setrecipient (Recipienttype.to,NewInternetAddress ("******@126.com"));//3 message content: Subject, ContentMsg.setsubject ("This is my mail from Java qq ....");//msg.setcontent ("Hello, no rain today!!!", "text/plain;charset=utf-8");//Plain TextMsg.setcontent ("Hello <a href= ' http://www.baidu.com?id=ddd ' > Hello, Happy?<a/>","Text/html;charset=utf-8");//HTML-formatted text //Send actionTransport.send (msg); } }
The second way:
Public class sendqqmail { Public Static void Main(string[] args)throwsException {Properties prop =NewProperties ();//Turn on debug debugging for viewing in the consoleProp.setproperty ("Mail.debug","true");//Set mail server host nameProp.setproperty ("Mail.host","Smtp.qq.com");//The Sending server needs authenticationProp.setproperty ("Mail.smtp.auth","true");//Send mail Agreement nameProp.setproperty ("Mail.transport.protocol","SMTP");//Turn on SSL encryption, or it will failMailsslsocketfactory SF =NewMailsslsocketfactory (); Sf.settrustallhosts (true); Prop.put ("Mail.smtp.ssl.enable","true"); Prop.put ("Mail.smtp.ssl.socketFactory", SF);//Create sessionSession session = Session.getinstance (prop);//Get Transport object by sessionTransport ts = Session.gettransport ();//Connect mail server: Mailbox type, account number, authorization code instead of password (more secure)Ts.connect ("Smtp.qq.com","619***629","Jnjt***bdab");//After the character is the authorization code, with the QQ password failed //Create mailMessage message = Createsimplemail (session);//Send mailTs.sendmessage (Message, message.getallrecipients ()); Ts.close (); }/** * @Method: Createsimplemail * @Description: Create a message that contains only text */ Public StaticMimeMessageCreatesimplemail(Session session)throwsException {//Create mail ObjectMimeMessage message =NewMimeMessage (session);//Indicates the sender of the messageMessage.setfrom (NewInternetAddress ("61*****[email protected]"));//Indicate the recipient of the messageMessage.setrecipient (Message.RecipientType.TO,NewInternetAddress ("*****@126.com"));//title of the messageMessage.setsubject ("QQ Mail Test");//e-mail text contentMessage.setcontent ("Send mail success!" ","Text/html;charset=utf-8");//Return to the created mail object returnMessage }}
QQ Mailbox Generation Authorization Code location:
126 Mailbox Receive results:
Send a message with an attachment
Relative to No attachments: use MimeBodyPart to build the body, add content to the body, attach. Finally, the use of Mimemultipart-addbodypart (body); Join the body.
A activation package is required here.
@Test//Send mail with attachments Public void Send2()throwsexception{//Establish a connection with the SMTP serverProperties p =NewProperties ();//Turn on debug debugging for viewing in the consoleP.setproperty ("Mail.debug","true"); P.setproperty ("Mail.host","Smtp.sina.com");//Specify mail server, default portP.setproperty ("Mail.smtp.auth","true");//To authenticate with the specified user name password //Send mail Agreement nameP.setproperty ("Mail.transport.protocol","SMTP");//Turn on SSL encryption, or it will failMailsslsocketfactory SF =NewMailsslsocketfactory (); Sf.settrustallhosts (true); P.put ("Mail.smtp.ssl.enable","true"); P.put ("Mail.smtp.ssl.socketFactory", SF);//Create sessionSession session = Session.getinstance (p);//Get Transport object by sessionTransport ts = Session.gettransport ();//Connect mail server: Mailbox type, account number, authorization code instead of password (more secure)Ts.connect ("Smtp.qq.com","61*****29","Jnjt*******bdab");//After the character is the authorization code, cannot use the QQ password //Declare a Message object (representing a message) and create it from the sessionMimeMessage msg =NewMimeMessage (session);//Mail message Encapsulation //1 SenderMsg.setfrom (NewInternetAddress ("61******[email protected]") );//2 RecipientsMsg.setrecipient (Recipienttype.to,NewInternetAddress ("Ch*****[email protected]") );//3 message content: Subject, ContentMsg.setsubject ("This is the mail I sent with Java--with attachments ....");//Add Attachment section //message Content Section 1---text contentMimeBodyPart body0 =NewMimeBodyPart ();//The text part of the messageBody0.setcontent ("Here are two <font color= ' red ' > pictures </font>,"Text/html;charset=utf-8");//message Content Section 2---Annex 1MimeBodyPart body1 =NewMimeBodyPart ();//Accessories 1Body1.setdatahandler (NewDataHandler (NewFiledatasource ("./imgs/1.jpg")) );//./represents the project root directoryBody1.setfilename (Mimeutility.encodetext ("Chinese 1.jpg") );//Chinese attachment name, solve garbled //message Content section 3---Annex 2MimeBodyPart Body2 =NewMimeBodyPart ();//Accessories 2Body2.setdatahandler (NewDataHandler (NewFiledatasource ("./imgs/2.jpg")) ); Body2.setfilename ("2.jpg");//Put the above 3 parts together and set into MSGMimemultipart mm =NewMimemultipart (); Mm.addbodypart (BODY0); Mm.addbodypart (BODY1); Mm.addbodypart (BODY2); Msg.setcontent (mm);//Send mailTs.sendmessage (Msg,msg.getallrecipients ()); Ts.close (); }
Receive results:
Small Knowledge Points:
1. You must first enable the POP3/STMP service in the QQ mailbox, then generate the authorization code
2. Import Mail.jar packages and activation packages
Mail.jar and Activation-1.1.0.jar Links:
Https://github.com/chenhaoxiang/Java/tree/master/JavaMail
3. To add code that turns on SSL encryption in the code (there is no mailsslsocketfactory class in the old version of mail)
4. Password is not QQ password, but authorization code!
Reprint Please specify source: http://blog.csdn.net/qq_26525215
This article is from the "university trip _ Remember the blog"
Java Mail---SMTP protocol-java e-mail (with attachments) presentation process