This article is the twelfth article of the vhr series, with the project address https://github.com/lenve/vhr
Email sending is also a common issue. Although the code is simple, many friends do not understand the process very well, so they still plan to talk to you about this topic.
Email Agreement
We often hear various email protocols, such as SMTP, POP3, and IMAP. So what are the functions of these protocols and what are the differences? Let’s discuss this issue first.
SMTP is an application-layer protocol based on TCP/IP. Its status is somewhat similar to HTTP. The default port number of the SMTP server is 25. Seeing this, friends may think that since the SMTP protocol is based on TCP/IP application layer protocol, can I also send an email through Socket? The answer is yes.
In life, we have to go through the following steps:
1. Xiao Wang from Shenzhen first delivered the email to the post office in Shenzhen
2. The post office in Shenzhen will deliver mail to the post office in Shanghai
3. Xiao Zhang from Shanghai came to the post office to pick up the mail
This is a reduced version of the mail sending process in life. These three steps can correspond to our email sending process separately. Suppose that emails are sent from [email protected] to [email protected]:
[email protected] first delivers the email to Tencent’s mail server
2. Tencent’s mail server delivers our mail to NetEase’s mail server
[email protected] Log in to NetEase's email server to view emails
Email delivery is roughly this process, which involves multiple protocols. Let’s take a look at it separately.
The full name of SMTP protocol is Simple Mail Transfer Protocol, which is translated as a simple mail transfer protocol. It defines the communication rules between the mail client software and the SMTP server and the SMTP server. In other words, the process of delivering emails to Tencent’s SMTP server first uses the SMTP protocol, and then Tencent’s SMTP server delivers emails to NetEase’s SMTP server still uses the SMTP protocol, which is used to receive emails. The full name of POP3 protocol is Post Office Protocol, which is translated as the Post Office Protocol. It defines the communication rules between the mail client and the POP3 server. So in what scenario will this protocol be used? When the email arrives at NetEase's SMTP server, the [email protected] user needs to log in to the server to view the email. At this time, the agreement is used: the email service provider will provide each user with a special email storage space. After the SMTP server receives the email, it saves the email to the corresponding user's email storage space. If the user wants to read the email, it needs to be completed through the email service provider's POP3 email server. Finally, some friends may have heard of the IMAP protocol, which is an extension of the POP3 protocol, with stronger functions and similar functions. I will not repeat it here.
Preparation for sending QQ emails
First of all, we need to log in to the QQ email web version and click the settings button above:
Then click the Accounts tab:
Find the option to enable POP3/SMTP in the Account tab, as follows:
Click to enable the relevant functions. The activation process requires mobile phone number verification. Just follow the steps and do not elaborate. After it is enabled successfully, you can obtain an authorization code, save the number and use it for a while.
Then we need the JavaxMail jar package. Friends can directly download it in Maven central warehouse. I won’t go to the following details here.
send
Simple email
If we only send a simple text, the sending method will be relatively simple. The whole process can be divided into three steps as follows:
Step 1: Construct the basic environment of the SMTP mail server
Properties properties = new Properties();properties.setProperty("mail.host", "smtp.qq.com");properties.setProperty("mail.transport.protocol", "smtp");properties.setProperty("mail.smtp.auth", "true");properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");properties.setProperty("mail.smtp.port", "465");Session session = Session.getDefaultInstance(properties); session.setDebug(true);Step 2: Construct the email
MimeMessage mimeMessage = new MimeMessage(session);mimeMessage.addRecipients(Message.RecipientType.TO, "[email protected]");//Set the recipient mimeMessage.addRecipients(Message.RecipientType.CC, "[email protected]");//Cc mimeMessage.setFrom("[email protected]");//Email sender mimeMessage.setSubject("Test email subject");//Email topic mimeMessage.setContent("Hello, this is a test email", "text/html;charset=utf-8");//Text
Step 3: Send email
Transport transport = session.getTransport();transport.connect("smtp.qq.com", "[email protected]", "The authorization code just applied for");transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());//Send an email, the second parameter is the recipient transport.close();Complex emails
When sending complex emails, the first and third steps are the same. Only the second step is more troublesome in constructing emails. Then, let me demonstrate to you an email that sends a picture and text + two attachments. To send complex emails, you must first be familiar with three concepts, as follows:
1.MimeMessage: This class is an email message that can understand MIME types and headers.
2.MimeMultipart: This class defines methods to add, delete and obtain different parts of the email
3.MimeBodyPart: This object represents a part of the contents of a MimeMessage object. Each MimeBodyPart is considered to have two parts: MIME type and content matching this type
The complete email generation process is as follows (see above for the first and third steps):
MimeMessage mimeMessage = new MimeMessage(session);mimeMessage.addRecipients(Message.RecipientType.TO, "[email protected]");//Set the recipient mimeMessage.addRecipients(Message.RecipientType.CC, "[email protected]");//Cc mimeMessage.setFrom("[email protected]");//Email sender mimeMessage.setSubject("Test email topic");//Email topic MimeMultipart mixed = new MimeMultipart("mixed");mimeMessage.setContent(mixed);//Set the MIME message body of the entire email into a mixed combination relationship MimeBodyPart attach1 = new MimeBodyPart();//Create attachment 1MimeBodyPart attach2 = new MimeBodyPart();//Create attachment 2MimeBodyPart content = new MimeBodyPart();//Create the email body mixed.addBodyPart(attach1);//Add Attachment One to the MIME message body mixed.addBodyPart(attach2);//Add Attachment Two to the MIME message body mixed.addBodyPart(content);//Add the body to the message body FileDataSource fds1 = new FileDataSource(new File("C://Users//sang//Desktop//1.png"));//Construct the data source of Attachment One DataHandler dh1 = new DataHandler(fds1);//Data processing attach1.setDataHandler(dh1);//Set the data source of attachment 1 attached1.setFileName("1.png");//Set the file name of attachment 1//The operation of attachment 2 is similar to attachment 1, so we will not comment each one here. FileDataSource fds2 = new FileDataSource(new File("C://Users//sang//Desktop//Blog Note.xlsx"));DataHandler dh2 = new DataHandler(fds2);attach2.setDataHandler(dh2);attach2.setFileName(MimeUtility.encodeText("Blog Note.xlsx"));//When setting the file name, if there is Chinese, you can encode it through the encodeText method in the MimeUtility class to avoid garbled MimeMultipart bodyMimeMultipart = new MimeMultipart("related");//Set the MIME type of the body content.setContent(bodyMimeMultipart);//Add bodyMimeMultipart to the body message body MimeBodyPart bodyPart = new MimeBodyPart();//HTML part of the bodyPart.setContent("<h1>Hello everyone, this is a test email <img src='cid:2.png'//</h1>","text/html;charset=utf-8");MimeBodyPart picPart = new MimeBodyPart();//The picture part of the bodyDataHandler dataHandler = new DataHandler(new FileDataSource("C://Users//sang//Desktop//2.png")); picPart.setDataHandler(dataHandler); picPart.setContentID("2.png");//Add the HTML and image parts of the body to bodyMimeMultipart.addBodyPart(bodyPart); bodyMimeMultipart.addBodyPart(picPart); mimeMessage.saveChanges();
OK, it is that simple to send QQ emails by Java Mail. As for other things such as 163, sina, etc., the writing style is similar, I will not elaborate on it here.
Summarize
The above is the implementation code of the QQ email function in SpringBoot introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!