The JavaMail API uses the javax.mail.Message class to represent a message. The Message class is an abstract class, so we need to use its subclass javax.mail.internet.MimeMessage class to create an instance object of the Message class. If we create a simple text message, then the MimeMessage class can meet our needs. However, if we need to create a complex email containing embedded resources or attachments, we need to use classes such as MimeMessage, javax.mail.internet.MimeBodyPart and javax.mail.internet.MimeMultipart in the JavaMail API.
1. MimeMessage class represents the entire email
2. The MimeBodyPart class represents a MIME message of the email
3. The MimeMultipart class represents a combined MIME message composed of multiple MIME messages.
The working relationship of these three classes is shown in the figure below:
Although application developers usually only need to use the three main classes: MimeMessage, MimeBodyPart and MimeMultipart when creating email content using JavaMailAPI, it is also necessary to understand their class inheritance relationship. The following figure lists the inheritance relationships and common methods of these three classes.
Next, use the javax.mail.internet.MimeMessage class to create a simple text message.
import java.util.Date;import java.util.Properties;import javax.mail.Message;import javax.mail.Session;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import java.io.FileOutputStream;public class TextMessage { public static void main(String[] args) throws Exception { String from = "[email protected]"; String to = "[email protected]"; String subject = "test"; String body = "test!!!"; // Create Session instance object Session session = Session.getDefaultInstance(new Properties()); // Create MimeMessage instance object MimeMessage msg = new MimeMessage(session); // Set sender msg.setFrom(new InternetAddress(from)); // Set recipient msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set sending date msg.setSentDate(new Date()); // Set the email subject msg.setSubject(subject); // Set the email body of plain text content msg.setText(body); // Save and generate the final email content msg.saveChanges(); // Write the contents of the MimeMessage object to the file msg.writeTo(new FileOutputStream("c://test.eml")); }}We use the email client (using foxmail here) to open the test.eml file under the C drive, and you can see the following information, indicating that our email was created successfully.
Here is a brief explanation of some of the classes that appear above
1. MimeMessage class: The above introduced that MimeMessage is a concrete implementation class of the Message class, which is used to create an instance object of the Message class. Here the constructor passes a Session object as a parameter;
2. Session class: This object is used to collect network connection information between the client and the mail server and define the environment information required to define the entire mail program. This information is stored in the Session object as the attributes of the Session object. The Session object uses the java.util.Properties object to obtain the mail server, username, password information and shared information that the entire application needs to use. Since the constructor of the Session class is private, we use the static factory method of getDefaultInstance() provided by the Session class to obtain a default Session object;
3. Properties class: This class represents a persistent property set, which is used to store the information of the key value pair as parameters to create a Session object. Here an empty set is constructed as a parameter;
4. InternetAddress class: This class is a subclass of the abstract class Address class, used to create an email address;
5. RecipientType class: This class is an internal class of the Message class. This class has 3 static variables. TO represents the recipient, CC represents the cc sender (the recipient knows the cc sender), and BCC represents the sender secret sender (the recipient does not know the sender secret sender).
The above email only contains simple text. Sometimes we need to use HTML files to enrich our email body, such as using HTML tags to type the email body, and using HTML tags to introduce some pictures or sounds into the email body. The following code creates an email containing HTML format
import java.util.Date;import java.util.Properties;import javax.mail.Message;import javax.mail.Session;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import java.io.FileOutputStream;public class HtmlMessage { public static void main(String[] args) throws Exception { String from = "[email protected]"; String to = "[email protected]"; String subject = "test"; String body = "<h4>Welcome to read this email</h4>"; // Create Session instance object Session session = Session.getDefaultInstance(new Properties()); // Create MimeMessage instance object MimeMessage msg = new MimeMessage(session); // Set sender msg.setFrom(new InternetAddress(from)); // Set recipient msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set sending date msg.setSentDate(new Date()); // Set the mail subject msg.setSubject(subject); // Set the HTML format email body msg.setContent(body, "text/html;charset=gb2312"); // Save and generate the final mail content msg.saveChanges(); // Write the contents of the MimeMessage object to the file msg.writeTo(new FileOutputStream("c://test.eml")); }}We will use foxmail to open test.eml, and the following display
The difference from the previous code is that when we set the email content, we use the setContent method instead of the setText method, and specify the MIME type of the email body as text/html.
Now we have learned to create emails with HTML tags, but sometimes we may need to insert some images into the email to express our meaning more intuitively. Then we need to use the MimeMultipart class and the MimeBodyPart class
import java.io.FileOutputStream;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Message;import javax.mail.Session;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;public class PictureMessage { public static void main(String[] args) throws Exception { String from = "[email protected]";// Sender address String to = "[email protected]"; // Recipient address String subject = "HTML email"; String body = "<a href=http://www.cnblogs.com>" + "Welcome to the Blog Garden</a></br>" + "<img src=/"c://dog.jpg/">"; Session session = Session.getDefaultInstance(new Properties()); // Create a MimeMessage object and set various message header fields MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); // Create a MimeMultipart object with subtype "related". MimeMultipart multipart = new MimeMultipart("related"); /* * Create a MimeBodyPart object representing the HTML body and add it to the MimeMultipart object created earlier*/ MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(body, "text/html;charset=gb2312"); multipart.addBodyPart(htmlBodyPart); /* * Create a MimeBodyPart object representing the content of the image and add it to the MimeMultipart object created earlier*/ MimeBodyPart gifBodyPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource("c://dog.jpg"); gifBodyPart.setFileName(fds.getName()); gifBodyPart.setDataHandler(new DataHandler(fds)); multipart.addBodyPart(gifBodyPart); /* * Set the MimeMultipart object to the content of the entire message, pay attention to calling the saveChanges method for updates*/ message.setContent(multipart); message.saveChanges(); // Write the contents of the MimeMessage object to the file message.writeTo(new FileOutputStream("c://PictureMessage.eml")); }}The code seems a bit complicated. You can take a look at the relationship diagram of the above-mentioned MimeMessage, MimeMultipart and MimeBodyPart. This will make it easier to understand the above code. We open PictureMessage.eml and see the following information, which shows that we have successfully created an email with a picture, and the image is included in the email in the form of an attachment.
MimeMultipart has two constructors.
public MimeMultipart()public MimeMultipart(String subtype)
The first one is parameterless, and the default instance object has a MIME type mixed. The second one formulates a type to create an instance object of the MimeMultipart class. There are three commonly used types: mixed, related, and alternative. The combination relationship of these three types in MIME is as follows:
Now we use the combination relationship shown above to create a message with an attachment and an embedded resource in the body.
import java.io.FileOutputStream;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Message;import javax.mail.Session;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;public class ComplexMessage { public static void main(String[] args) throws Exception { Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = createMessage(session); message.writeTo(new FileOutputStream("c://ComplexMessage.eml")); } public static MimeMessage createMessage(Session session) throws Exception { String from = "[email protected]";// Sender address String to = "[email protected]"; // Recipient address String subject = "HTML email"; // Email subject String body = "<a href=http://www.cnblogs.com>" + "Welcome to the blog park</a></br>" + "<img src=/"c://dog.jpg/">"; MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); // Create each MimeBodyPart object representing the message body and attachment MimeBodyPart contentPart = createContent(body, "c://dog.jpg"); // The following attachment can be video or audio MimeBodyPart attachPart1 = createAttachment("c://music.MP3"); MimeBodyPart attachPart2 = createAttachment("c://video.avi"); // Create a MimeMultipart object for combining the message body and attachment MimeMultipart allMultipart = new MimeMultipart("mixed"); allMultipart.addBodyPart(contentPart); allMultipart.addBodyPart(attachPart1); allMultipart.addBodyPart(attachPart2); // Set the entire email content to the final combined MimeMultipart object message.setContent(allMultipart); message.saveChanges(); return message; } public static MimeBodyPart createContent(String body, String filename) throws Exception { /* * Create a MimeMultipart object representing the combined MIME message, and the MimeBodyPart object to which the MimeMultipart object is saved*/ MimeBodyPart contentPart = new MimeBodyPart(); MimeMultipart contentMultipart = new MimeMultipart("related"); /* * Create a MimeBodyPart object to save the HTML body and save it to MimeMultipart*/ MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(body, "text/html;charset=gb2312"); contentMultipart.addBodyPart(htmlBodyPart); /* * Create a MimeBodyPart object to save the picture and save it to MimeMultipart*/ MimeBodyPart gifBodyPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filename); gifBodyPart.setDataHandler(new DataHandler(fds)); contentMultipart.addBodyPart(gifBodyPart); // Save the MimeMultipart object to the MimeBodyPart object contentPart.setContent(contentMultipart); return contentPart; } public static MimeBodyPart createAttachment(String filename) throws Exception { // Create a MimeBodyPart object that saves the attachment, and add the attachment content and corresponding information MimeBodyPart attachPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filename); attachPart.setDataHandler(new DataHandler(fds)); attachPart.setFileName(fds.getName()); return attachPart; }}Open the ComplexMessage.eml file and you can see the following content:
Now we have learned how to create a plain text email, an email with HTML format, and an email with embedded images and attachments. The next article will introduce how to send emails JavaMail Getting Started with the Third Article Send Email
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.