Detailed message Implementation (iv)------JavaMail send (with pictures and attachments) and receive mail

Source: Internet
Author: User
Tags auth imap all mail mail account

Well, into the main steps of this series of tutorials, the theoretical knowledge of the previous e-mail we all know, then this blog we will use the code to complete the delivery of the message. This is very widely used in real projects, such as registration needs to send mail for account activation, such as OA project using mail for task reminders and so on. What we're talking about here is the ability to use JavaMail to send and receive messages.

PS: This blog source download link: https://github.com/YSOcean/cnblogs

1, JavaMail Introduction

JavaMail is a standard development package provided by Sun Corporation (now acquired by Oracle) to facilitate the delivery and reception of mail in applications by Java developers, and it supports a number of commonly used mail protocols, such as the previous Smtp,pop3,imap, mime, and so on. When writing a message using the JavaMail API, we do not have to consider the underlying implementation details of the message, as long as the corresponding API class in the JavaMail development package is called.

Javamail:https://github.com/javaee/javamail/releases

  

Download this version of JavaMail, which contains the implementation of SMTP, IMAP, and POP3 protocols.

2. JavaMail API

The JavaMail API can be divided into three main categories according to the following functions:

①, creating and parsing mail APIs

②, sending the mail API

③, receiving the Mail API

The above three types of APIs are made up of multiple classes in JavaMail, but there are four core classes, and it's easy to write Java mail handlers when we write programs and remember these four core classes.

  

①, Message class: The Javax.mail.Message class is the core API for creating and parsing messages, an abstract class that typically uses its subclass Javax.mail.internet.MimeMessage class. Its instance object represents an e-mail message. When a client program sends a message, it first uses the JavaMail API that created the message to create a message object that encapsulates the message data, and then passes the object to the mail sending API (Transport Class) for delivery. When a client program receives a message, the message receiving API encapsulates the received message data in an instance of the message class, which is used by the client program to parse the received message data from the object using the message resolution API.

②, Transport class: The Javax.mail.Transport class is the core API class for sending mail, and its instance object represents a mail-sending object that implements a mail-sending protocol, such as the SMTP protocol, after the client program creates a good message object, Just use the Mail sending API to get the Transport object, and then pass the message object to the Transport object and call its Send method to send it to the specified SMTP server.

③, Store class: The Javax.mail.Store class is the core API class that receives mail, its instance object represents the message receiving object that implements a message receiving protocol, such as the POP3 protocol, when the client program receives the message, it only needs to get the Store object using the mail receiving API. Then call the Store object's Receive method, you can obtain the message data from the specified POP3 server, and encapsulate the message data into a Message object that represents the messages.

④, Session class: The Javax.mail.Session class is used to define the environment information required for the entire application and to collect session information from the client to establish a network connection to the mail server, such as the host name of the mail server, the port number, the mail sending and receiving protocol, and so on. This information is used by the Session object to build Transport and Store objects for sending and receiving messages, and to provide information support when creating message objects for clients.

  

3. Use JavaMail to send simple plain text messages

In understanding the following code implementation of the message sent, we can send the message supposedly as a rocket carrying this satellite sent. The message is a satellite, Transport is a rocket, and the construction of satellites and rockets need the help of the Session, such a relationship more convenient to remember.

Package Com.ys.mail;import Java.io.objectinputstream.getfield;import Java.util.date;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.addressexception;import Javax.mail.internet.internetaddress;import Javax.mail.internet.mimemessage;import Javax.swing.text.html.minimalhtmlwriter;public class Sendmailtext {//Sender address public static String senderaddress = "[Email  protected] ";//Recipient address public static String recipientaddress =" [email protected] ";//Sender account name public static string senderaccount = "xxx";//Sender account password public static String Senderpassword = "xxx";p ublic static void Main (string[] args) t Hrows Exception {///1, the parameter configuration of the connection mail server Properties props = new properties ();//Set the authentication method for the user props.setproperty ("Mail.smtp.auth", " True ");//Set the Transport protocol Props.setproperty (" Mail.transport.protocol "," SMTP ");//Set the sender's SMTP server address Props.setproperty (" Mail.smtp.host "," smtp.163.com ");//2, createSession object that defines the environment information required for the entire application session session = Session.getinstance (props);//Set debug information to print out the console Session.setdebug (true);//3, Creates an instance object of the message msg = Getmimemessage (session),//4, gets the message transfer object according to the session object Transporttransport transport = Session.gettransport ();//Set the sender's account name and password Transport.connect (Senderaccount, Senderpassword);//Send mail and send to all recipient addresses, Message.getallrecipients () gets all the recipients that were added when the message object was created, Cc, BCC transport.sendmessage (msg,msg.getallrecipients ());// If you only want to send to the specified person, you can do the following//transport.sendmessage (MSG, new Address[]{new internetaddress ("[email protected]")});//5, Close mail connection Transport.close ();} /** * Get an instance object that creates a message * @param session * @return * @throws messagingexception * @throws addressexception */public static M Imemessage Getmimemessage (Session session) throws exception{//create an instance object of a message mimemessage msg = new MimeMessage (session);// Set the sender address Msg.setfrom (new internetaddress (senderaddress)),/** * Set the recipient address (can add multiple recipients, Cc, BCC), that is, the following line of code to write more than one line * MimeMessage.RecipientType.TO: Send * MimeMessage.RecipientType.CC: CC * MIMEMESSAGE.RECIPIENTTYpe. BCC: Secret Delivery */msg.setrecipient (mimemessage.recipienttype.to,new internetaddress (recipientaddress));// Set the message subject Msg.setsubject ("Message subject", "UTF-8");//Set the message body msg.setcontent ("Simple plain text mail! "," Text/html;charset=utf-8 ");//Set the sending time of the message, send Msg.setsentdate (New Date ()) by default; return msg;}}

The above code has detailed comments, we do not know how to leave a message. Note: Please change the recipient, sender and other information to your own when you run.

After executing the above code, then we look at the inbox:

  

Then a simple plain text file is sent out.

4. Mail sending problem

①, Sender's mailbox account name and password: Some mailbox set up a separate password, and some must use authorization code login (QQ mailbox), which in the manual experience SMTP and POP3 protocol this blog has been introduced.

②, the sender's SMTP server address: Generally smtp.xxx.com, such as 163 mailbox is SMTP.163.COM,QQ mailbox is smtp.qq.com.

③, possibly your recipient address, sender address and other information are correct, the console also printed the correct information, but in the Inbox is not receiving information. This is because the Inbox server may not be able to find the email that you sent (for example, if you think your email is an ad), which may be found in the trash. The solution is to repeat the contents of the message not to send multiple times, or to change the inbox to try.

④, this instance is using the JavaMail1.6 version, the supported JDK must be the jdk1.7 version!!!

5. Receive mail using JavaMail

Since there is not much use in receiving mail, here is a simple example:

Package Com.ys.mail;import Java.util.properties;import Javax.mail.address;import javax.mail.folder;import Javax.mail.message;import Javax.mail.session;import Javax.mail.store;public class Recipientmail {//Recipient address public static string recipientaddress = "[email protected]";//Recipient account name public static string recipientaccount = "xxx";// Recipient account password public static String Recipientpassword = "xxx";p ublic static void Main (string[] args) throws Exception {//1, connecting mail server The parameter configuration Properties props = new properties ();//Set the Transport protocol Props.setproperty ("Mail.store.protocol", "POP3");// Set the recipient's POP3 server Props.setproperty ("Mail.pop3.host", "pop3.163.com");//2, create a Session object that defines the environment information required for the entire application session session = Session.getinstance (props);//Set debug information to print out the console//session.setdebug (true); Store store = Session.getstore ("POP3");//Connect recipient POP3 Server Store.connect ("pop3.163.com", Recipientaccount, Recipientpassword);//Obtain the user's mail account, note that the name of a mail folder obtained through the POP3 protocol can only be Inboxfolder folder = Store.getfolder ("Inbox");// Set the access rights to the mail account Folder.open (folder.read_write);//Get all mail information for the mail account Message [] messages = Folder.getmessages (); for (int i = 0; i < messages.length; i++) {//Get message subject string subject = Messages[i ].getsubject ();//Get Mail sender address[] from = Messages[i].getfrom ();//Get the message content (HTML code that contains the message content) String content = (string) Messages[i].getcontent ();} Close the Mail Folder object Folder.close ();//Close Connection object Store.close ();}}

  

6. Use JavaMail to send messages with pictures and attachments

Let's look at the project structure and include pictures and attachments in the SRC directory:

  

Then look at the code:

Package Com.ys.mail;import Java.util.date;import Java.util.properties;import javax.activation.datahandler;import Javax.activation.filedatasource;import Javax.mail.message;import Javax.mail.messagingexception;import Javax.mail.session;import Javax.mail.transport;import Javax.mail.internet.addressexception;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; public class Sendmailtext_picture_enclosure {//Sender address public static String senderaddress = "[email protected]";// Recipient address public static string recipientaddress = "[email protected]";//Sender account name public static string senderaccount = "XXX" ;//Sender account password public static String Senderpassword = "xxx";p ublic static void Main (string[] args) throws Exception {//1, connecting mail server The parameter configuration Properties props = new properties ();//Set the authentication method of the user Props.setproperty ("Mail.smtp.auth", "true");// Set the transport protocol Props.setproperty ("MAIL.TRANSPOrt.protocol "," SMTP "),//Set the sender's SMTP server address Props.setproperty (" Mail.smtp.host "," smtp.163.com ");//2, Create a Session object that defines the environment information required for the entire application session session = Session.getinstance (props);//Set debug information to print out the console Session.setdebug (TRUE);// 3. Create an instance object of the message msg = Getmimemessage (session);//4, gets the message transfer object according to the session object Transporttransport transport = Session.gettransport ();//Set the sender's account name and password Transport.connect (Senderaccount, Senderpassword);//Send mail and send to all recipient addresses, Message.getallrecipients () gets all the recipients that were added when the message object was created, Cc, BCC transport.sendmessage (Msg,msg.getallrecipients ()),//5, Close mail connection Transport.close ();} /** * Get an instance object that creates a message * @param session * @return * @throws messagingexception * @throws addressexception */public static M Imemessage Getmimemessage (Session session) throws EXCEPTION{//1. Creating an instance object of a message mimemessage msg = new MimeMessage (session) ;//2. Set the sender address Msg.setfrom (new internetaddress (senderaddress));/** * 3. Set the recipient address (you can add multiple recipients, Cc, BCC), that is, the following line of code to write more than one line * MimeMessage.RecipientType.TO: Send * MimeMessage.RecipientType.CC: CC * MimeMessage.RecipientType.BCC: Bcc */msg.setrecipient (mimemessage.recipienttype.to,new internetaddress (recipientaddress));//4. Set the message subject Msg.setsubject ("Mail subject (including pictures and attachments)", "UTF-8");//The following is the set message body//msg.setcontent ("Simple plain text mail! "," Text/html;charset=utf-8 ");//5.        Create picture "Node" mimebodypart image = new MimeBodyPart ();         Read local file DataHandler dh = new DataHandler (New Filedatasource ("Src\\mailtestpic.png"));         Add picture data to "node" Image.setdatahandler (DH);             Set a unique number for node (the ID is referenced in the text "node") Image.setcontentid ("Mailtestpic"); 6.        Create text "Node" MimeBodyPart text = new MimeBodyPart (); The way to add a picture here is to include the entire picture in the message content, or you can actually add the network picture as an HTTP link text.setcontent ("This is a picture <br/><a href= ' Http://www.cnblo        Gs.com/ysocean/p/7666061.html ' ></a> ', ' text/html;charset=utf-8 '); 7.        (text + picture) sets the relationship between the text and the picture "node" (combining text and picture "node" into a mixed "node") Mimemultipart mm_text_image = new Mimemultipart ();        Mm_text_image.addbodypart (text); Mm_text_image.addbodypart (image);    Mm_text_image.setsubtype ("related"); Association relationship//8. The mixed "node" of the text + picture is encapsulated into a normal "node"//Content that is eventually added to the message is composed of multiple bodypart Multipart, so what we need is bodypart,//Mailte above        Stpic is not bodypart, all to wrap mm_text_image into a bodypart mimebodypart text_image = new MimeBodyPart ();                Text_image.setcontent (Mm_text_image); 9.        Create attachment "Node" mimebodypart attachment = new MimeBodyPart ();        Read local file DataHandler DH2 = new DataHandler (New Filedatasource ("Src\\mailtestdoc.docx"));        Add the attachment data to the node Attachment.setdatahandler (DH2);                        Set the file name of the attachment (requires encoding) Attachment.setfilename (Mimeutility.encodetext (Dh2.getname ())); 10.        Set (text + picture) and attachment relationship (synthesize a large mixed "node"/Multipart) Mimemultipart mm = new Mimemultipart ();        Mm.addbodypart (Text_image);     Mm.addbodypart (attachment);         If you have multiple attachments, you can create multiple add-Mm.setsubtype ("mixed") more than once. Mixed relationship//11. Set up a relationship for an entire message(Add the final mixed "node" as the content of the message to the mail object) msg.setcontent (mm);//Set the sending time of the message, send Msg.setsentdate (New Date ()) by default; return msg;}} 

After executing the program, we check the mailbox:

  

Then a message containing the image (click on the image to jump to the specified hyperlink), and the attachment is generated.

  

Detailed message Implementation (iv)------JavaMail send (with pictures and attachments) and receive mail

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.