JAVA mail sending details
To realize the mail function on the network, there must be a special mail server.
These mail servers are similar to the post office in real life. It is mainly responsible for receiving the mail delivered by users and delivering the mail to the email of the mail recipient.
SMTP server address: generally smtp.xxx.com, for example, 163 email is smtp.163.com, QQ email is smtp.qq.com
E-mail needs to be applied on the e-mail server. For example, if we want to use QQ mailbox, we need to activate the mailbox function.
transport protocol
SMTP protocol
Send email:
Generally, the server that processes user SMTP requests (mail sending requests) is called SMTP server (mail sending server).
POP3 protocol
Receiving email:
Generally, the server that processes user POP3 requests (mail receiving requests) is called POP3 server (mail receiving server)
Principle of mail receiving and sending
- Zhang San connects to the smtp server through the smtp protocol, and then sends an email to Netease's email server
- Netease analysis found that the e-mail server that needs to go to QQ is an smtp server that forwards the e-mail to QQ through the smtp protocol
- QQ stores the received mail in 3314291346@qq.com In the space of this email account
- Li Si connects to pop3 server through pop3 protocol to receive emails
- from 3314261346@qq.com Get mail from this mailbox
- The pop3 server sends the extracted mail to Li Si
[Note:] it's possible that everything you receive is correct, but you just can't receive the email. It may be that the inbox server rejected the email you sent (it's considered as spam email advertisement), which can be found in the garbage can or can't be found. Only try changing your inbox.
Java send mail
summary
We will use the code to send the email. This is widely used in practical projects, such as sending email for account activation when registering, and using email for task reminder in 0A project.
Sending E-mail using Java is very simple, but first you should prepare the JavaMail API and Java Activation Framework.
Get two jar packages:
- mail.jar
- activation.jar
<!-- maven Import and its convenience--> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency>
JavaMail is a set of standard development packages provided by sun company (now acquired by Oracle) to facilitate Java developers to realize the function of sending and receiving mail in applications. It supports some commonly used mail protocols, such as SMTP, POP3, IMAP, MIME, etc. When we use JavaMail API to write mail, we don't need to consider the underlying implementation details of mail, just call the corresponding API classes in JavaMail development kit.
We can try to send a simple email first to ensure that the computer can connect to the network.
- Create a Session object that contains the network connection information of the mail server.
- Create a Message object representing the Message content
- Create a Transport object, connect to the server, send a Message, and close the connection
There are mainly four core classes. When we write programs, it is easy to write Java mail processing programs by remembering the four core classes.
Let's first understand the whole process and then look at the code.
1. Create a session object
2. Create a Transport object
3. Use the user name and authorization code of the mailbox to connect to the mail server
4. Create a Message object (session needs to be delivered)
message needs to indicate the sender, recipient and file content
5. Send email
6. Close the connection
code
package com.cetus.mail; import com.sun.mail.util.MailSSLSocketFactory; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.security.GeneralSecurityException; import java.util.Properties; public class MailDemo01 { public static void main(String[] args) throws Exception { Properties prop=new Properties(); prop.setProperty("mail.host","smtp.qq.com");///Set up QQ mail server prop.setProperty("mail.transport.protocol","smtp");///Mail sending protocol prop.setProperty("mail.smtp.auth","true");//Need to verify user password //SSL encryption is required for QQ mailbox, which is only available for QQ mailbox MailSSLSocketFactory sf=new MailSSLSocketFactory(); //Note the mail class when importing packages here sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable","true"); prop.put("mail.smtp.ssl.socketFactory",sf); //Five steps to send mail using javaMail //1. Create a session object that defines the environment information required by the entire application Session session=Session.getDefaultInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("XXXX@qq.com","Authorization code"); } }); //Turn on the debug mode of the session, so that you can view the running status of the Email sent by the program session.setDebug(true); //2. Get the transport object through session Transport ts=session.getTransport(); //3. Use the user name and authorization code of the mailbox to connect to the mail server ts.connect("smtp.qq.com","XXXX@qq.com","Authorization code"); //4. Create email: write file //Note that the session needs to be passed MimeMessage message=new MimeMessage(session); //Indicate the sender of the message message.setFrom(new InternetAddress("XXXX@qq.com")); //Indicate the recipient of the message message.setRecipient(Message.RecipientType.TO,new InternetAddress("XXXX@qq.com")); //Message title message.setSubject("Sent title"); //Text content of the message message.setContent("content","text/html;charset=UTF-8"); //5. Send email ts.sendMessage(message,message.getAllRecipients()); //6. Close the connection ts.close(); } }
Code with pictures and attachments
First recognize two classes and a noun:
MIME (Multipurpose Internet mail extension type)
MimeBodyPart class
javax.mail.internet. The mibodypart class represents a MIME message. Like the MimeMessage class, it inherits from the Part interface.
MimeMultipart class
javax.mail.internet.MimeMultipart is an implementation subclass of the abstract class Multipart, which is used to combine multiple MIME messages. A MimeMultipart object can contain multiple MimeBodyPart objects representing MIME messages.
Code: the code is the same as before, but the text content of the email is modified to the following code
Picture insertion:
//=================================Prepare picture data MimeBodyPart image=new MimeBodyPart(); //Pictures need to be processed by data DataHandler dh=new DataHandler(new FileDataSource("D:1.jpg")); //Put the data of the processed image in part image.setDataHandler(dh); //Set an ID name for this part image.setContentID("bz.jpg"); //Prepare data for text MimeBodyPart text=new MimeBodyPart(); text.setContent("This is a text<img src='cid:bz.jpg'>","text/html;charset=UTF-8");//cid: setContentID above //Describe data relationships MimeMultipart mm=new MimeMultipart(); mm.addBodyPart(text); mm.addBodyPart(image); mm.setSubType("related"); //This indicates the type range of email attachments sent //Set it in the message and save the modification message.setContent(mm); message.saveChanges();
Attachment insertion:
//=================================Prepare picture data MimeBodyPart image=new MimeBodyPart(); //Pictures need to be processed by data DataHandler dh=new DataHandler(new FileDataSource("D:1.jpg")); //Put the data of the processed image in part image.setDataHandler(dh); //Set an ID name for this part image.setContentID("bz.jpg"); //=================================Prepare body data MimeBodyPart text=new MimeBodyPart(); text.setContent("This is a text<img src='cid:bz.jpg'>","text/html;charset=UTF-8"); //=================================Prepare attachment data MimeBodyPart body1= new MimeBodyPart(); body1.setDataHandler(new DataHandler(new FileDataSource("D:\\Bert\\cmd.txt"))); body1.setFileName("1.txt"); //Describe data relationships MimeMultipart mm=new MimeMultipart(); mm.addBodyPart(body1); mm.addBodyPart(text); mm.addBodyPart(image); mm.setSubType("mixed"); //This indicates the type range of email attachments sent //Set it in the message and save the modification message.setContent(mm); message.saveChanges();
Then you can run!!! If you want to show it in a web page, you can also write it as a javaweb project. It should be noted that in order to meet the three second principle of user experience (this is learned from madness 🤪), It takes a lot of time to connect to the mail server, and there are too many registrants, so threads are usually used to run. Clicking send will throw it to the user's page waiting for the message to be sent, and the work of connecting to the server is still in progress.
public class Servlet extends javax.servlet.http.HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) { //Processing front-end requests String username = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); //Encapsulate information into user objects User user = new User(username, password, email); SendMail sendMail = new SendMail(user); sendMail.start(); //Start thread request.setAttribute("msg","Sent successfully"); try { request.getRequestDispatcher("msg.jsp").forward(request,response); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }