Overview
1. Email-related standards
The JavaMail service programs provided by manufacturers can selectively implement certain mail protocols, common mail protocols include:
SMTP (Simple Mail Transfer Protocol) is a simple mail transfer protocol. It is a set of rules for transmitting mail from the source address to the destination address. It controls the transit method of letters.
POP3 (Post Office Protocol Version 3): It is a standard protocol used to receive emails.
IMAP (Internet Mail Access Protocol): that is, Internet mail access protocol. It is an alternative protocol for POP3.
These three protocols have protocols corresponding to SSL encrypted transmission, namely SMTPS, POP3S and IMAPS.
MIME (Multipurpose Internet Mail Extensions): that is, the multipurpose Internet mail extension standard. It is not a mail transfer protocol. However, the format is defined for messages, attachments and other contents that are transmitted.
2. Introduction to JavaMail
JavaMail is an API published by Sun to handle email. It is not included in Java SE, but is part of Java EE.
mail.jar: This JAR file contains the JavaMail API and Sun-provided SMTP, IMAP, and POP3 service providers;
activation.jar: This JAR file contains implementations of the JAF API and Sun.
The core classes used in JavaMail packages for processing emails are: Properties, Session, Message, Address, Authenticator, Transport, Store, etc.
3. Mail transfer process
As shown in the above picture, the steps for processing emails are as follows:
4. Message structure
MimeMessage class: represents the entire email.
MimeBodyPart class: A MIME message representing the message.
MimeMultipart class: Represents a combined MIME information composed of multiple MIME information.
5. The core class of JavaMail
JavaMail provides a high-level abstraction of sending and receiving emails, forming some key interfaces and classes, which form the basis of the program. Let’s take a look at these most common objects.
6. java.util.Properties class (property object)
The java.util.Properties class represents a set of properties.
Each of its keys and values is of type String.
Since JavaMail needs to communicate with the mail server, this requires the program to provide a lot of information such as server address, port, username, password, etc. JavaMail encapsulates these attribute information through the Properties object.
Example: For example, the following code encapsulates several attribute information:
Properties prop = new Properties();prop.setProperty("mail.debug", "true");prop.setProperty("mail.host", "[email protected]");prop.setProperty("mail.transport.protocol", "smtp");prop.setProperty("mail.smtp.auth", "true");For different mail protocols, JavaMail stipulates that service providers must support a series of attributes.
The following table is some common attributes (the attribute values are set as String type, and the attribute type bar only indicates how the attributes are parsed):
7. javax.mail.Session class (session object)
Session represents a mail session.
The main functions of Session include two aspects:
Receive various configuration attribute information: attribute information set through the Properties object;
Initialize the JavaMail environment: Initialize the JavaMail environment according to the JavaMail configuration file to create instances of other important classes through the Session object.
JavaMail provides basic configuration information through the following files in the META-INF directory of the Jar package so that session can load the provider's implementation class according to this configuration file:
javamail.default.providers;
javamail.default.address.map .
example:
Properties props = new Properties();props.setProperty("mail.transport.protocol", "smtp");Session session = Session.getInstance(props);8. javax.mail.Transport class (mail transfer)
There are only two ways to handle email operations: sending or receiving.
JavaMail describes these two different operations as transmission ( javax.mail.Transport ) and storage ( javax.mail.Store ), transmitting the sending of the corresponding mail, and storing the receiving of the corresponding mail.
getTransport: getTransport () in the Session class has multiple overloaded methods that can be used to create Transport objects.
connect: If the authentication command - mail.smtp.auth is set, then when connecting to the server using the connect method of the Transport class, the user name and password must be added.
sendMessage: The sendMessage method of the Transport class is used to send mail messages.
close: The close method of the Transport class is used to close the connection to the mail server.
9. javax.mail.Store class (mail storage)
getStore: getStore() in the Session class has multiple overloaded methods that can be used to create Store objects.
connect: If the authentication command - mail.smtp.auth is set, then when connecting to the server using the connect method of the Store class, the user name and password must be added.
getFolder: The getFolder method of the Store class can obtain the folder Folder object in the mailbox.
close: The close method of the Store class is used to close the connection to the mail server.
10. javax.mail.Message(message object)
javax.mail.Message is an abstract class that can only be instantiated by subclasses, and in most cases it is javax.mail.internet.MimeMessage.
MimeMessage represents an email message of MIME type.
To create a Message, you need to pass the Session object to the MimeMessage constructor:
MimeMessage message = new MimeMessage(session);
Note: There are other constructors, such as using input streams in RFC822 format to create messages.
setFrom: Set the sender of the email
setRecipient: Set the sender, cc person, and secret person of the email
The three predefined address types are:
Message.RecipientType.TO: Recipient
Message.RecipientType.CC: cc person
Message.RecipientType.BCC: Secretly give away
setSubject: Set the subject of the email
setContent: Set the mail content
setText: If the email content is plain text, you can use this interface to set the text content.
10. javax.mail.Address(address)
Once you have created Session and Message and filled in the message, you can use Address to determine the mail address. Like Message, Address is also an abstract class. You are using the javax.mail.internet.InternetAddress class.
If the created address only contains an email address, just pass the email address to the constructor.
example:
Address address = new InternetAddress("[email protected]");
Authenticator: Certified
Like the java.net class, the JavaMail API can also utilize Authenticator to access protected resources through username and password. For the JavaMail API, these resources are mail servers. JavaMail Authenticator is in the javax.mail package, and it is different from the class Authenticator with the same name in java.net. The two do not share the same Authenticator because the JavaMail API is used for Java 1.1, and it does not have the java.net category.
To use Authenticator, first create a subclass of the abstract class and return a PasswordAuthentication instance from the getPasswordAuthentication() method. After creation is complete, you must register Authenticator with session. Then, when authentication is required, Authenticator will be notified. You can pop up windows or read usernames and passwords from a configuration file (although it is not secure to not encrypt) and return them to the calling program as PasswordAuthentication objects.
example:
Properties props = new Properties();Authenticator auth = new MyAuthenticator();Session session = Session.getDefaultInstance(props, auth);
Example
Send text mail
public static void main(String[] args) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.debug", "true"); prop.setProperty("mail.host", MAIL_SERVER_HOST); prop.setProperty("mail.transport.protocol", "smtp"); prop.setProperty("mail.smtp.auth", "true"); // 1. Create session Session session = Session.getInstance(prop); Transport ts = null; // 2. Get the transport object through session ts = session.getTransport(); // 3. Connect to the mail server ts.connect(MAIL_SERVER_HOST, USER, PASSWORD); // 4. Create a message MimeMessage message = new MimeMessage(session); // Email message header message.setFrom(new InternetAddress(MAIL_FROM)); // Sender of the message.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); // The recipient of the email message.setRecipient(Message.RecipientType.CC, new InternetAddress(MAIL_CC)); // The cc message.setRecipient(Message.RecipientType.BCC, new InternetAddress(MAIL_BCC)); // The message sender message.setSubject("Test text email"); // The title of the email // The message message.setText("Unparalleled in the world."); // 5. Send mail ts.sendMessage(message, message.getAllRecipients()); ts.close();}Send HTML-formatted emails
public static void main(String[] args) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.debug", "true"); prop.setProperty("mail.host", MAIL_SERVER_HOST); prop.setProperty("mail.transport.protocol", "smtp"); prop.setProperty("mail.smtp.auth", "true"); // 1. Create session Session session = Session.getInstance(prop); Transport ts = null; // 2. Get the transport object through session ts = session.getTransport(); // 3. Connect to the mail server ts.connect(MAIL_SERVER_HOST, USER, PASSWORD); // 4. Create a message MimeMessage message = new MimeMessage(session); // Email message header message.setFrom(new InternetAddress(MAIL_FROM)); // Sender of the message.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); // The recipient of the email message.setRecipient(Message.RecipientType.CC, new InternetAddress(MAIL_CC)); // The cc message.setRecipient(Message.RecipientType.BCC, new InternetAddress(MAIL_BCC)); // The recipient of the email message.setSubject("Test HTML mail"); // The title of the email String htmlContent = "<h1>Hello</h1>" + "<p>Show the picture <img src='cid:abc.jpg'>1.jpg</p>"; MimeBodyPart text = new MimeBodyPart(); text.setContent(htmlContent, "text/html;charset=UTF-8"); MimeBodyPart image = new MimeBodyPart(); DataHandler dh = new DataHandler(new FileDataSource("D://[04]Temp//img//1.jpg")); image.setDataHandler(dh); image.setContentID("abc.jpg"); // Describe the data relationship MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(text); mm.addBodyPart(image); mm.setSubType("related"); message.setContent(mm); message.saveChanges(); // 5. Send mail ts.sendMessage(message, message.getAllRecipients()); ts.close();}Send emails with attachments
public static void main(String[] args) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.debug", "true"); prop.setProperty("mail.host", MAIL_SERVER_HOST); prop.setProperty("mail.transport.protocol", "smtp"); prop.setProperty("mail.smtp.auth", "true"); // 1. Create session Session session = Session.getInstance(prop); Transport ts = null; // 2. Get the transport object through session ts = session.getTransport(); // 3. Connect to the mail server ts.connect(MAIL_SERVER_HOST, USER, PASSWORD); // 4. Create a message MimeMessage message = new MimeMessage(session); // Email message header message.setFrom(new InternetAddress(MAIL_FROM)); // Sender of the message.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); // The recipient of the email message.setRecipient(Message.RecipientType.CC, new InternetAddress(MAIL_CC)); // The cc message.setRecipient(Message.RecipientType.BCC, new InternetAddress(MAIL_BCC)); // The recipient of the email message.setSubject("Test with attachment mail"); // The title of the email MimeBodyPart text = new MimeBodyPart(); text.setContent("There are two attachments in the email.", "text/html;charset=UTF-8"); // Describe the data relationship MimeMultipart mm = new MimeMultipart(); mm.setSubType("related"); mm.addBodyPart(text); String[] files = { "D://[04]Temp//img//1.jpg", "D://[04]Temp//img//2.jpg" }; // Add an email attachment for (String filename : files) { MimeBodyPart attachPart = new MimeBodyPart(); attachPart.attachFile(filename); mm.addBodyPart(attachPart); } message.setContent(mm); message.saveChanges(); // 5. Send mail ts.sendMessage(message, message.getAllRecipients()); ts.close();}Get emails in your mailbox
public class StoreMail { final static String USER = "robot"; // Username final static String PASSWORD = "password520"; // Password public final static String MAIL_SERVER_HOST = "mail.***.com"; // Mailbox server public final static String TYPE_HTML = "text/html;charset=UTF-8"; // Text content type public final static String MAIL_FROM = "[email protected]"; // Sender public final static String MAIL_TO = "[email protected]"; // To the recipient public final static String MAIL_CC = "[email protected]"; // Cc person public final static String MAIL_BCC = "[email protected]"; // Secretly send public static void main(String[] args) throws Exception { // Create a Properties object with specific connection information Properties prop = new Properties(); prop.setProperty("mail.debug", "true"); prop.setProperty("mail.store.protocol", "pop3"); prop.setProperty("mail.pop3.host", MAIL_SERVER_HOST); // 1. Create session Session session session = Session.getInstance(prop); // 2. Get the Store object through session Store store = session.getStore(); // 3. Connect to the mail server store.connect(MAIL_SERVER_HOST, USER, PASSWORD); // 4. Get the mail folder in the mailbox Folder folder = store.getFolder("inbox"); folder.open(Folder.READ_ONLY); // Get all messages in the folder Message objects Message[] messages = folder.getMessages(); for (int i = 0; i < messages.length; i++) { String subject = messages[i].getSubject(); String from = (messages[i].getFrom()[0]).toString(); System.out.println("Th" + (i + 1) + "The subject of the message: " + subject); System.out.println("Th" + (i + 1) + "The sender address of the email: " + from); } // 5. Close folder.close(false); store.close(); }}Forward email
Example: Get the first email under the specified mail folder and forward it
public static void main(String[] args) throws Exception { Properties prop = new Properties(); prop.put("mail.store.protocol", "pop3"); prop.put("mail.pop3.host", MAIL_SERVER_HOST); prop.put("mail.pop3.starttls.enable", "true"); prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.host", MAIL_SERVER_HOST); // 1. Create session Session session = Session.getDefaultInstance(prop); // 2. Read the mail folder Store store = session.getStore("pop3"); store.connect(MAIL_SERVER_HOST, USER, PASSWORD); Folder folder = store.getFolder("inbox"); folder.open(Folder.READ_ONLY); // Get the first email message in the mail folder Message[] messages = folder.getMessages(); if (messages.length <= 0) { return; } Message message = messages[0]; // Print key message String from = InternetAddress.toString(message.getFrom()); if (from != null) { System.out.println("From: " + from); } String replyTo = InternetAddress.toString(message.getReplyTo()); if (replyTo != null) { System.out.println("Reply-to: " + replyTo); } String to = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO)); if (to != null) { System.out.println("To: " + to); } String subject = message.getSubject(); if (subject != null) { System.out.println("Subject: " + subject); } Date sent = message.getSentDate(); if (sent != null) { System.out.println("Sent: " + sent); } // Set forward email message header Message forward = new MimeMessage(session); forward.setFrom(new InternetAddress(MAIL_FROM)); forward.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); forward.setSubject("Fwd: " + message.getSubject()); // Set forward email content MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(message, "message/rfc822"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); forward.setContent(multipart); forward.saveChanges(); Transport ts = session.getTransport("smtp"); ts.connect(USER, PASSWORD); ts.sendMessage(forward, forward.getAllRecipients()); folder.close(false); store.close(); ts.close(); System.out.println("message forwarded successfully...");}The above is all about this article. I hope it will be helpful for everyone to learn how to send and receive emails by javamail.