Engineering
"Code Instance"
Packagecom. Higgin.mail.demo;ImportJava.io.File;Importjava.util.Properties;ImportJavax.mail.Authenticator;Importjavax.mail.MessagingException;Importjavax.mail.PasswordAuthentication;Importjavax.mail.Session;ImportJavax.mail.Transport;Importjavax.mail.internet.AddressException;Importjavax.mail.internet.InternetAddress;ImportJavax.mail.internet.MimeBodyPart;ImportJavax.mail.internet.MimeMessage;ImportJavax.mail.internet.MimeMessage.RecipientType;ImportJavax.mail.internet.MimeMultipart;Importjavax.mail.internet.MimeUtility;Importorg.junit.Test; Public classJavaMailDemo02 {@Test Public voidTESTDEMO01 ()throwsaddressexception, messagingexception{/*** 1. Get session * **/Properties Props=NewProperties (); Props.setproperty ("Mail.host", "smtp.163.com");//Set mail server addressProps.setproperty ("Mail.smtp.auth", "true");//set whether the mail server requires login authenticationAuthenticator auth=NewAuthenticator () {//Creating the Authenticator Publicpasswordauthentication getpasswordauthentication () {return NewPasswordauthentication ("Mailbox User name", "email password");//user name and password } }; Session Session=session.getinstance (Props,auth);//Get Session Object /*** 2. Create MimeMessage * **/mimemessage msg=NewMimeMessage (session);//Create a Mail objectMsg.setfrom (NewInternetAddress ("[email protected]");//Set SenderMsg.addrecipient (Recipienttype.to,NewInternetAddress ("Zhang San @126.com"));//Set RecipientMsg.addrecipient (recipienttype.cc,NewInternetAddress ("John Doe @qq.com"));//Set up Recipients (cc)Msg.addrecipient (RECIPIENTTYPE.BCC,NewInternetAddress ("Harry @163.com"));//set the recipient (dark Send)Msg.setsubject ("This is a test message 2");//set the title of the sent message//Specify the message content, and the MIME type of the contentMimemultipart partlist=NewMimemultipart (); Msg.setcontent (partlist); //set the contents of the message to a multipart collection object//Create a Part 1MimeBodyPart part1=NewMimeBodyPart (); //assigning content to a partPart1.setcontent ("Another test message", "Text/html;charset=utf-8"); //add a part to the collectionPartlist.addbodypart (part1); //Create a Part 2MimeBodyPart part2=NewMimeBodyPart (); //assigning attachments to partsPart2.attachfile (NewFile ("c:/. jpg")); //Specify the name of the attachmentPart2.setfilename (Mimeutility.encodetext ("Andy Lau. jpg"));//solve Chinese garbled characters//add a part to the collectionPartlist.addbodypart (part2); /*** 3. Send mail * **/transport.send (msg); }}
01_javamail_04_ Send mail with attachments