Overview
1, mail-related standards
The JavaMail service program provided by the manufacturer can selectively implement certain mail protocols, and common mail protocols include:
SMTP (Simple Mail Transfer Protocol): The Easy Mail Transfer Protocol, which is a set of rules for sending messages from source to destination to control how the letters are transferred.
POP3 (Post Office Protocol–version 3): Post Office Protocol version 3, a standard protocol for receiving e-mail messages.
IMAP (Internet Mail access Protocol): The Internet Mail Access Protocol. is a POP3 alternative agreement.
All three protocols have protocols for SSL encrypted transmission, namely SMTPS, Pop3s and Imaps.
MIME (Multipurpose Internet Mail Extensions): The Multipurpose Internet Mail Extension standard. It is not a mail transfer protocol. However, a format is defined for messages, attachments, and their contents that transmit content.
2, JavaMail Introduction
JavaMail is an API released by Sun to process emails. It is not included in the Java SE, but as 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 the JAF API and the Sun implementation.
The core classes used in JavaMail packages are: Properties, session, message, address, authenticator, transport, Store, etc.
3. Message transfer process
As shown in the figure above, the e-mail processing steps are as follows:
- Creates a session object.
- The session object creates a transport object/store object that is used to send/save messages.
- Transport object/store object to connect to the mail server.
- Transport object/store object to create a message object (that is, mail content).
- The transport object sends a message, and the Store object gets the mail message for the mailbox.
4. Message structure
MimeMessage class: Represents the entire message.
MimeBodyPart class: Represents a MIME message for a message.
Mimemultipart class: Represents a combination of MIME information that is synthesized by multiple MIME information groups.
5, the core class of JavaMail
JavaMail an advanced abstraction of the email, forming some of the key interfaces and classes that form the basis of the program, let's take a look at these most common objects separately.
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.
Because JavaMail needs to communicate with the mail server, this requires that the program provide many information, such as server address, port, username, password, etc., JavaMail encapsulate the property information through the Properties object.
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 range of attributes,
The following table is some of the common properties (property values are set with the String type, and the property type bar only indicates how the property is parsed):
7, Javax.mail.Session Class (Session object)
A session represents a mail conversation.
The main functions of the session include two aspects:
Receive various configuration attribute information: Property information set by properties object;
Initialize the JavaMail environment: initializes the JavaMail environment based on the JavaMail configuration file to create instances of other important classes through the session object.
JavaMail, in the Meta-inf directory of the Jar package, provides basic configuration information through the following files so that the session can load the provider's implementation classes according to this profile:
Javamail.default.providers;
Javamail.default.address.map.
Cases:
Properties Props = new properties ();
Props.setproperty ("Mail.transport.protocol", "SMTP");
Session session = Session.getinstance (props);
8, Javax.mail.Transport Class (mail transmission)
The mail operation only sends or receives two kinds of processing methods.
JavaMail describes these two different operations as transport (Javax.mail.Transport) and Storage (Javax.mail.Store), transmits the corresponding message, and stores the receipt of the corresponding message.
The Gettransport () in the Gettransport:session class has multiple overloaded methods that you can use to create transport objects.
Connect: If you set the authentication command--mail.smtp.auth, you must add a username and password when you connect to the server using the Connect method of the transport class.
The SendMessage method of the Sendmessage:transport class is used to send mail messages.
The Close method of the Close:transport class is used to shut down the connection to the mail server.
9, Javax.mail.Store class (mail storage)
The GetStore () in the Getstore:session class has multiple overloaded methods that you can use to create a Store object.
Connect: If you set the authentication command--mail.smtp.auth, you must add a username and password when you connect to the server using the Connect method of the Store class.
The GetFolder method of the Getfolder:store class can get the Mail folder folder object in the mailbox
The Close method of the Close:store class is used to shut down the connection to the mail server.
10, Javax.mail.Message (Message object)
Javax.mail.Message is an abstract class that can only be instantiated with subclasses, mostly javax.mail.internet.MimeMessage.
MimeMessage an e-mail message that represents a 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 creating messages with an input stream in RFC822 format.
Setfrom: Set the sender of the message
Setrecipient: Set the sender of the message, CC, the secret to send a person
The three predefined address types are:
Message.RecipientType.TO: Recipient
Message.RecipientType.CC: CC Person
Message.RecipientType.BCC: The secret to send people
Setsubject: Set the subject of the message
SetContent: Set the content of the message
SetText: If the message content is plain text, you can use this interface to set the text content.
10, javax.mail.Address (address)
Once you have created the session and message and filled it in with messages, you can use address to determine the mailing addresses. As with the message, the address is an abstract class. You are using the Javax.mail.internet.InternetAddress class.
If you create an address that contains only e-mail addresses, you can simply pass the e-mail address to the builder.
Cases:
Address = new InternetAddress ("[email protected]");
Authenticator: Certified by
As with the Java.net class, the JavaMail API can also use authenticator to access protected resources through user names and passwords. For the JavaMail API, these resources are mail servers. The JavaMail authenticator is in the Javax.mail package, and it differs 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 in Java 1.1, and it does not have java.net categories.
To use authenticator, first create a subclass of an abstract class and return the Passwordauthentication instance from the Getpasswordauthentication () method. After the creation is complete, you must register authenticator with the session. Then, when you need authentication, you will notify authenticator. You can eject the window, or you can read the username and password from the configuration file (although no encryption is unsafe) and return them as passwordauthentication objects to the calling program.
Cases:
Properties Props = new properties ();
Authenticator auth = new Myauthenticator ();
Session session = Session.getdefaultinstance (props, auth);
Instance
Send a text message
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, to create session sessions session = Session.getinstance (prop);
Transport ts = null;
2, through session to get transport object ts = Session.gettransport ();
3, connected to the mail server Ts.connect (mail_server_host, USER, PASSWORD);
4, create mail mimemessage message = new MimeMessage (session); Mail message header Message.setfrom (new InternetAddress (Mail_from)); The sender of the message message.setrecipient (Message.RecipientType.TO, New InternetAddress (mail_to)); The recipient of the message message.setrecipient (Message.RecipientType.CC, New InternetAddress (MAIL_CC)); CC Message.setrecipient of the message (Message.RecipientType.BCC, new InternetAddress (MAIL_BCC)); The Message.setsubject of the message ("Test text mail"); The message's title//Mail message body message.settext ("unparalleled.")
"); 5, Send mail Ts.sendmessage (messagE, message.getallrecipients ());
Ts.close ();
}
Send HTML-formatted messages
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, to create session sessions session = Session.getinstance (prop);
Transport ts = null;
2, through session to get transport object ts = Session.gettransport ();
3, connected to the mail server Ts.connect (mail_server_host, USER, PASSWORD);
4, create mail mimemessage message = new MimeMessage (session); Mail message header Message.setfrom (new InternetAddress (Mail_from)); The sender of the message message.setrecipient (Message.RecipientType.TO, New InternetAddress (mail_to)); The recipient of the message message.setrecipient (Message.RecipientType.CC, New InternetAddress (MAIL_CC)); CC Message.setrecipient of the message (Message.RecipientType.BCC, new InternetAddress (MAIL_BCC)); The Message.setsubject of the message ("Test HTML mail"); Message title String htmlcontent = "
send messages 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, to create session sessions session = Session.getinstance (prop);
Transport ts = null;
2, through session to get transport object ts = Session.gettransport ();
3, connected to the mail server Ts.connect (mail_server_host, USER, PASSWORD);
4, create mail mimemessage message = new MimeMessage (session); Mail message header Message.setfrom (new InternetAddress (Mail_from)); The sender of the message message.setrecipient (Message.RecipientType.TO, New InternetAddress (mail_to)); The recipient of the message message.setrecipient (Message.RecipientType.CC, New InternetAddress (MAIL_CC)); CC Message.setrecipient of the message (Message.RecipientType.BCC, new InternetAddress (MAIL_BCC)); Mail Message.setsubject ("Test with Attachment mail");
The header of the message mimebodypart Text = new MimeBodyPart (); Text.setcontent ("There are two attachments in the message.) ", "Text/html;charset=utf-8");
Descriptive 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 message 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 messages in a mailbox
public class StoreMail {final static string user = "Robot";//user name final static string PASSWORD = "password520";//Secret Code 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]"; Recipient public final static String mail_cc = "[email protected]"; CC people public final static String mail_bcc = "[email protected]"; The secret sender public static void main (string[] args) throws Exception {///Create a Properties object with specific connection information properties prop = new Pr
Operties ();
Prop.setproperty ("Mail.debug", "true");
Prop.setproperty ("Mail.store.protocol", "POP3");
Prop.setproperty ("Mail.pop3.host", mail_server_host);
1, to create session sessions session = Session.getinstance (prop);
2, through the session to get store object Store store = Session.getstore (); 3, connected to the mail server Store.connect (mail_server_host, USER, PASSword);
4, get mail Folder folder = Store.getfolder ("Inbox");
Folder.open (folder.read_only);
Get all mail message objects within folder 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 ("First" + (i + 1) + "message Subject:" + subject);
System.out.println ("The first" + (i + 1) + "The sender address of the email:" + from);
}//5, close Folder.close (false);
Store.close ();
}
}
Forwarding messages
Example: Gets the first message under the specified message folder and forwards
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, to create session sessions session = Session.getdefaultinstance (prop);
2, read 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 1th message in the Mail folder message[] messages = Folder.getmessages ();
if (messages.length <= 0) {return;
} message = Messages[0];
Print Message key information 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 forwarding 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 forwarding message 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 the entire content of this article, I hope to learn javamail to send and receive mail methods to help.