


Detailed explanation of how to send pictures and attachments and receive emails using JavaMail
This article mainly introduces in detail the implementation of sending and receiving emails with pictures and attachments in JavaMail. It has a certain reference value. Interested friends can refer to it.
Okay, enter this This is the most important step in the series of tutorials. We all understand the theoretical knowledge of emails in the previous article, so in this blog we will use code to complete the sending of emails. This is widely used in actual projects. For example, registration requires sending an email for account activation. Another example is the use of emails for task reminders in OA projects. What we are talking about here is to use JavaMail to complete the sending and receiving functions of emails.
PS: The source code download link for this blog: https://github.com/YSOcean/cnblogs
1. Introduction to JavaMail
JavaMail is Sun (now acquired by Oracle) provides a set of standard development kits to facilitate Java developers to implement email sending and receiving functions in applications. It supports some commonly used email protocols, such as SMTP and POP3 mentioned earlier. IMAP, MIME, etc. When we use the JavaMail API to write emails, we do not need to consider the underlying implementation details of the email. We only need to call the corresponding API class in the JavaMail development kit.
JavaMail download address: https://github.com/javaee/javamail/releases
Download this version of JavaMail, including SMTP, IMAP, and implementation of the POP3 protocol.
2. JavaMail API
The JavaMail API can be divided into the following three categories according to its functions:
① API for creating and parsing emails
②、API for sending emails
③、API for receiving emails
The above three types of APIs are composed of multiple classes in JavaMail, but there are mainly four core classes. , when we write a program, we can easily write a Java mail processing program by remembering these four core classes.
①. Message class: javax.mail.Message class is the core API for creating and parsing emails. This is an abstract class, and its subclass javax.mail is usually used. .internet.MimeMessage class. Its instance object represents an email. When the client program sends an email, it first uses the JavaMail API that creates the email to create a Message object that encapsulates the email data, and then passes this object to the email sending API (Transport class) for sending. When the client program receives mail, the mail receiving API encapsulates the received mail data in an instance of the Message class. The client program uses the mail parsing API to parse the received mail data from this object.
②. Transport class: javax.mail.Transport class is the core API class for sending mail. Its instance object represents the mail sending object that implements a certain mail sending protocol, such as SMTP protocol. The client program creates After getting the Message object, you only need to use the mail sending API to get the Transport object, then pass the Message object to the Transport object and call its sending method to send the mail to the specified SMTP server.
③Store class: javax.mail.Store class is the core API class for receiving mail. Its instance object represents a mail receiving object that implements a certain mail receiving protocol, such as POP3 protocol, and the client program receives When receiving mail, you only need to use the mail receiving API to obtain the Store object, and then call the receiving method of the Store object to obtain the mail data from the specified POP3 server, and encapsulate the mail data into the Message object representing the mail.
④. Session class: javax.mail.Session class is used to define the environment information required by the entire application, and to collect session information for the client to establish a network connection with the mail server, such as the host name of the mail server, Port number, email sending and receiving protocol used, etc. The Session object builds Transport and Store objects for sending and receiving emails based on this information, and provides information support when creating Message objects for the client.
3. Use JavaMail to send a simple plain text email
When understanding the following code to implement email sending, we can imagine the email sending as a rocket carrying the satellite send. Among them, Message is a satellite, and Transport is a rocket. The construction of satellites and rockets requires the help of Session. This relationship is easier 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 { //发件人地址 public static String senderAddress = "xxx@163.com"; //收件人地址 public static String recipientAddress = "xxx@qq.com"; //发件人账户名 public static String senderAccount = "xxx"; //发件人账户密码 public static String senderPassword = "xxx"; public static void main(String[] args) throws Exception { //1、连接邮件服务器的参数配置 Properties props = new Properties(); //设置用户的认证方式 props.setProperty("mail.smtp.auth", "true"); //设置传输协议 props.setProperty("mail.transport.protocol", "smtp"); //设置发件人的SMTP服务器地址 props.setProperty("mail.smtp.host", "smtp.163.com"); //2、创建定义整个应用程序所需的环境信息的 Session 对象 Session session = Session.getInstance(props); //设置调试信息在控制台打印出来 session.setDebug(true); //3、创建邮件的实例对象 Message msg = getMimeMessage(session); //4、根据session对象获取邮件传输对象Transport Transport transport = session.getTransport(); //设置发件人的账户名和密码 transport.connect(senderAccount, senderPassword); //发送邮件,并发送到所有收件人地址,message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人 transport.sendMessage(msg,msg.getAllRecipients()); //如果只想发送给指定的人,可以如下写法 //transport.sendMessage(msg, new Address[]{new InternetAddress("xxx@qq.com")}); //5、关闭邮件连接 transport.close(); } /** * 获得创建一封邮件的实例对象 * @param session * @return * @throws MessagingException * @throws AddressException */ public static MimeMessage getMimeMessage(Session session) throws Exception{ //创建一封邮件的实例对象 MimeMessage msg = new MimeMessage(session); //设置发件人地址 msg.setFrom(new InternetAddress(senderAddress)); /** * 设置收件人地址(可以增加多个收件人、抄送、密送),即下面这一行代码书写多行 * MimeMessage.RecipientType.TO:发送 * MimeMessage.RecipientType.CC:抄送 * MimeMessage.RecipientType.BCC:密送 */ msg.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(recipientAddress)); //设置邮件主题 msg.setSubject("邮件主题","UTF-8"); //设置邮件正文 msg.setContent("简单的纯文本邮件!", "text/html;charset=UTF-8"); //设置邮件的发送时间,默认立即发送 msg.setSentDate(new Date()); return msg; } }
The above code has detailed comments. If you don’t understand, you can leave a message. Note: Please change the recipient, sender and other information to your own when running.
After executing the above code, then we check the inbox:
Then a simple plain text file has been sent.
4. Problems with sending emails
①. The sender’s email account name and password: Some emails have separate passwords, and others must log in with an authorization code. (qq mailbox), which is introduced in the blog Manual experience of SMTP and pop3 protocols.
②、发件人的SMTP服务器地址:一般是 smtp.xxx.com,比如163邮箱是smtp.163.com,qq邮箱是smtp.qq.com。
③、有可能你收件人地址,发件人地址等信息都正确了,控制台也打印了正确的信息,但是在收件箱就是收不到信息。这是因为可能收件箱服务器拒收了你发的邮件(比如认为你的邮件是广告),这时候可能在垃圾箱里能找到,可能找不到。解决办法是重复的邮件内容不要多次发送,或者更换收件箱试试。
④、本实例使用的是JavaMail1.6版本,支持的JDK必须是jdk1.7版本!!!
5、使用 JavaMail 接收邮件
由于接收邮件的用处不多,这里我们就简单的给出一个实例:
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 { //收件人地址 public static String recipientAddress = "xxx@163.com"; //收件人账户名 public static String recipientAccount = "xxx"; //收件人账户密码 public static String recipientPassword = "xxx"; public static void main(String[] args) throws Exception { //1、连接邮件服务器的参数配置 Properties props = new Properties(); //设置传输协议 props.setProperty("mail.store.protocol", "pop3"); //设置收件人的POP3服务器 props.setProperty("mail.pop3.host", "pop3.163.com"); //2、创建定义整个应用程序所需的环境信息的 Session 对象 Session session = Session.getInstance(props); //设置调试信息在控制台打印出来 //session.setDebug(true); Store store = session.getStore("pop3"); //连接收件人POP3服务器 store.connect("pop3.163.com", recipientAccount, recipientPassword); //获得用户的邮件账户,注意通过pop3协议获取某个邮件夹的名称只能为inbox Folder folder = store.getFolder("inbox"); //设置对邮件账户的访问权限 folder.open(Folder.READ_WRITE); //得到邮件账户的所有邮件信息 Message [] messages = folder.getMessages(); for(int i = 0 ; i < messages.length ; i++){ //获得邮件主题 String subject = messages[i].getSubject(); //获得邮件发件人 Address[] from = messages[i].getFrom(); //获取邮件内容(包含邮件内容的html代码) String content = (String) messages[i].getContent(); } //关闭邮件夹对象 folder.close(); //关闭连接对象 store.close(); } }
6、使用 JavaMail 发送带图片、附件的邮件
我们先看项目结构,在src目录下包含图片和附件:
然后看代码:
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 { //发件人地址 public static String senderAddress = "xxx@163.com"; //收件人地址 public static String recipientAddress = "xxx@qq.com"; //发件人账户名 public static String senderAccount = "xxx"; //发件人账户密码 public static String senderPassword = "xxx"; public static void main(String[] args) throws Exception { //1、连接邮件服务器的参数配置 Properties props = new Properties(); //设置用户的认证方式 props.setProperty("mail.smtp.auth", "true"); //设置传输协议 props.setProperty("mail.transport.protocol", "smtp"); //设置发件人的SMTP服务器地址 props.setProperty("mail.smtp.host", "smtp.163.com"); //2、创建定义整个应用程序所需的环境信息的 Session 对象 Session session = Session.getInstance(props); //设置调试信息在控制台打印出来 session.setDebug(true); //3、创建邮件的实例对象 Message msg = getMimeMessage(session); //4、根据session对象获取邮件传输对象Transport Transport transport = session.getTransport(); //设置发件人的账户名和密码 transport.connect(senderAccount, senderPassword); //发送邮件,并发送到所有收件人地址,message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人 transport.sendMessage(msg,msg.getAllRecipients()); //5、关闭邮件连接 transport.close(); } /** * 获得创建一封邮件的实例对象 * @param session * @return * @throws MessagingException * @throws AddressException */ public static MimeMessage getMimeMessage(Session session) throws Exception{ //1.创建一封邮件的实例对象 MimeMessage msg = new MimeMessage(session); //2.设置发件人地址 msg.setFrom(new InternetAddress(senderAddress)); /** * 3.设置收件人地址(可以增加多个收件人、抄送、密送),即下面这一行代码书写多行 * MimeMessage.RecipientType.TO:发送 * MimeMessage.RecipientType.CC:抄送 * MimeMessage.RecipientType.BCC:密送 */ msg.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(recipientAddress)); //4.设置邮件主题 msg.setSubject("邮件主题(包含图片和附件)","UTF-8"); //下面是设置邮件正文 //msg.setContent("简单的纯文本邮件!", "text/html;charset=UTF-8"); // 5. 创建图片"节点" MimeBodyPart image = new MimeBodyPart(); // 读取本地文件 DataHandler dh = new DataHandler(new FileDataSource("src\\mailTestPic.png")); // 将图片数据添加到"节点" image.setDataHandler(dh); // 为"节点"设置一个唯一编号(在文本"节点"将引用该ID) image.setContentID("mailTestPic"); // 6. 创建文本"节点" MimeBodyPart text = new MimeBodyPart(); // 这里添加图片的方式是将整个图片包含到邮件内容中, 实际上也可以以 http 链接的形式添加网络图片 text.setContent("这是一张图片<br/><a href='http://www.cnblogs.com/ysocean/p/7666061.html'><img src='cid:mailTestPic'/></a>", "text/html;charset=UTF-8"); // 7. (文本+图片)设置 文本 和 图片"节点"的关系(将 文本 和 图片"节点"合成一个混合"节点") MimeMultipart mm_text_image = new MimeMultipart(); mm_text_image.addBodyPart(text); mm_text_image.addBodyPart(image); mm_text_image.setSubType("related"); // 关联关系 // 8. 将 文本+图片 的混合"节点"封装成一个普通"节点" // 最终添加到邮件的 Content 是由多个 BodyPart 组成的 Multipart, 所以我们需要的是 BodyPart, // 上面的 mailTestPic 并非 BodyPart, 所有要把 mm_text_image 封装成一个 BodyPart MimeBodyPart text_image = new MimeBodyPart(); text_image.setContent(mm_text_image); // 9. 创建附件"节点" MimeBodyPart attachment = new MimeBodyPart(); // 读取本地文件 DataHandler dh2 = new DataHandler(new FileDataSource("src\\mailTestDoc.docx")); // 将附件数据添加到"节点" attachment.setDataHandler(dh2); // 设置附件的文件名(需要编码) attachment.setFileName(MimeUtility.encodeText(dh2.getName())); // 10. 设置(文本+图片)和 附件 的关系(合成一个大的混合"节点" / Multipart ) MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(text_image); mm.addBodyPart(attachment); // 如果有多个附件,可以创建多个多次添加 mm.setSubType("mixed"); // 混合关系 // 11. 设置整个邮件的关系(将最终的混合"节点"作为邮件的内容添加到邮件对象) msg.setContent(mm); //设置邮件的发送时间,默认立即发送 msg.setSentDate(new Date()); return msg; } }
执行程序后,我们查看邮箱:
那么一封包含图片(点击图片跳转到指定超链接),和附件的邮件就生成了。
The above is the detailed content of Detailed explanation of how to send pictures and attachments and receive emails using JavaMail. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

With the continuous development of social media, Xiaohongshu has become a platform for more and more young people to share their lives and discover beautiful things. Many users are troubled by auto-save issues when posting images. So, how to solve this problem? 1. How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? 1. Clear the cache First, we can try to clear the cache data of Xiaohongshu. The steps are as follows: (1) Open Xiaohongshu and click the "My" button in the lower right corner; (2) On the personal center page, find "Settings" and click it; (3) Scroll down and find the "Clear Cache" option. Click OK. After clearing the cache, re-enter Xiaohongshu and try to post pictures to see if the automatic saving problem is solved. 2. Update the Xiaohongshu version to ensure that your Xiaohongshu

With the popularity of Douyin short videos, user interactions in the comment area have become more colorful. Some users wish to share images in comments to better express their opinions or emotions. So, how to post pictures in TikTok comments? This article will answer this question in detail and provide you with some related tips and precautions. 1. How to post pictures in Douyin comments? 1. Open Douyin: First, you need to open Douyin APP and log in to your account. 2. Find the comment area: When browsing or posting a short video, find the place where you want to comment and click the "Comment" button. 3. Enter your comment content: Enter your comment content in the comment area. 4. Choose to send a picture: In the interface for entering comment content, you will see a "picture" button or a "+" button, click

Apple's recent iPhones capture memories with crisp detail, saturation and brightness. But sometimes, you may encounter some issues that may cause the image to look less clear. While autofocus on iPhone cameras has come a long way, allowing you to take photos quickly, the camera can mistakenly focus on the wrong subject in certain situations, making the photo blurry in unwanted areas. If your photos on your iPhone look out of focus or lack sharpness overall, the following post should help you make them sharper. How to Make Pictures Clearer on iPhone [6 Methods] You can try using the native Photos app to clean up your photos. If you want more features and options

In PowerPoint, it is a common technique to display pictures one by one, which can be achieved by setting animation effects. This guide details the steps to implement this technique, including basic setup, image insertion, adding animation, and adjusting animation order and timing. Additionally, advanced settings and adjustments are provided, such as using triggers, adjusting animation speed and order, and previewing animation effects. By following these steps and tips, users can easily set up pictures to appear one after another in PowerPoint, thereby enhancing the visual impact of the presentation and grabbing the attention of the audience.

Overview of advanced functions of how to use HTML, CSS and jQuery to implement image merge display: In web design, image display is an important link, and image merge display is one of the common techniques to improve page loading speed and enhance user experience. This article will introduce how to use HTML, CSS and jQuery to implement advanced functions of image merging and display, and provide specific code examples. 1. HTML layout: First, we need to create a container in HTML to display the merged images. You can use di

Some netizens found that when they opened the browser web page, the pictures on the web page could not be loaded for a long time. What happened? I checked that the network is normal, so where is the problem? The editor below will introduce to you six solutions to the problem that web page images cannot be loaded. Web page images cannot be loaded: 1. Internet speed problem The web page cannot display images. It may be because the computer's Internet speed is relatively slow and there are more softwares opened on the computer. And the images we access are relatively large, which may be due to loading timeout. As a result, the picture cannot be displayed. You can turn off the software that consumes more network speed. You can go to the task manager to check. 2. Too many visitors. If the webpage cannot display pictures, it may be because the webpages we visited were visited at the same time.

When using WPS office software, we found that not only one form is used, tables and pictures can be added to the text, pictures can also be added to the table, etc. These are all used together to make the content of the entire document look richer. , if you need to insert two pictures into the document and they need to be arranged side by side. Our next course can solve this problem: how to place two pictures side by side in a wps document. 1. First, you need to open the WPS software and find the picture you want to adjust. Left-click the picture and a menu bar will pop up, select "Page Layout". 2. Select "Tight wrapping" in text wrapping. 3. After all the pictures you need are confirmed to be set to "Tight text wrapping", you can drag the pictures to the appropriate position and click on the first picture.

Are you also using Foxit PDF Reader software? So do you know how Foxit PDF Reader converts pdf documents into jpg images? The following article brings you how Foxit PDF Reader converts pdf documents into jpg images. For those who are interested in the method of converting jpg images, please come and take a look below. First start Foxit PDF Reader, then find "Features" on the top toolbar, and then select the "PDF to Others" function. Next, open a web page called "Foxit PDF Online Conversion". Click the "Login" button on the upper right side of the page to log in, and then turn on the "PDF to Image" function. Then click the upload button and add the pdf file you want to convert into an image. After adding it, click "Start Conversion"
