Java Mail Sending
Principle of E-mail Sending
We write to pen pals:
Write a letter - > Put it in the mailbox - > pick it up at the local post office - > Pass it to the post office where the recipient is located - > Put the envelope in the mailbox of the recipient's family - > Pen pal gets the letter in the mailbox - > Read the letter
Similarly, when we send e-mail to others, we also need an e-mail office, that is, mail server. The qq mailbox and Netease mailbox we use are like mailboxes for sending envelopes.
Mail Server
-
SMTP Server (Mail Sender): Server that handles user mail send (smtp) requests
The address of the SMTP server is generally smtp.xxx.com,For example, the QQ mailbox is smtp.qq.com..
-
POP3 Server (Mail Receiving Server): Server that handles user mail receiving (pop3) requests
Example: I want to send an email to my Netease mailbox (aaa@163.com) through my QQ mailbox (0000000000@qq.com).
Sending mail in Java
First we need to prepare the JavaMail API and the Java Activation Framework.
Get two jar packages:
- mail.jar
- activation.jar
JavaMail is a standard development package provided by Sun Company to facilitate Java developers to implement mail sending and receiving functions in applications. It supports common mail protocols, such as SMTP, POP3, etc.
Because I use qq mailbox, to get the permission of qq mailbox, I will get an authorization code.
Remember the authorization code.
Guide Pack
Send text only
package priv.sehun.mail; import com.sun.mail.util.MailSSLSocketFactory; import java.security.GeneralSecurityException; import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendMail { public static void main(String[] args) throws GeneralSecurityException, MessagingException { Properties properties = new Properties(); properties.setProperty("mail.host", "smtp.qq.com"); properties.setProperty("mail.transport.protocol", "smtp"); properties.setProperty("mail.smtp.auth", "true"); //QQ mailbox to set up SSL encryption, fixed code MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getDefaultInstance(properties, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { //Sender mail username, authorization code return new PasswordAuthentication("15********@qq.com", "Your own authorization code"); } }); //1. Open Session's debug mode so that you can see the running status of the program sending Email. session.setDebug(true); Transport ts = session.getTransport(); //Connect to mail server using mailbox username and authorization code ts.connect("smtp.qq.com", "15********@qq.com", "Your own authorization code"); //Create mail objects MimeMessage message = new MimeMessage(session); //Identify the sender of the mail message.setFrom(new InternetAddress("15********@qq.com")); //Identify the recipient of the mail message.setRecipient(Message.RecipientType.TO, new InternetAddress("12********@qq.com")); //Title of mail message.setSubject("Good morning, cp"); //Text content of mail message.setContent("You have to be happy.^-^", "text/html;charset=UTF-8"); //Send mail ts.sendMessage(message, message.getAllRecipients()); ts.close(); } }
Send mail with pictures and attachments
package priv.sehun.mail; import com.sun.mail.util.MailSSLSocketFactory; import java.security.GeneralSecurityException; import java.util.*; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; public class SendMail2 { public static void main(String[] args) throws GeneralSecurityException, MessagingException { Properties properties = new Properties(); properties.setProperty("mail.host", "smtp.qq.com"); properties.setProperty("mail.transport.protocol", "smtp"); properties.setProperty("mail.smtp.auth", "true"); MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getDefaultInstance(properties, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { //Sender mail username, authorization code return new PasswordAuthentication("15********@qq.com", "Authorization code"); } }); //Open Session's debug mode so that you can see the running status of the program sending Email session.setDebug(true); Transport ts = session.getTransport(); //Connect to mail server using mailbox username and authorization code ts.connect("smtp.qq.com", "15********@qq.com", "Authorization code"); //Create mail objects MimeMessage message = getMimeMessage(session); //Send mail ts.sendMessage(message, message.getAllRecipients()); ts.close(); } private static MimeMessage getMimeMessage(Session session) throws MessagingException { MimeMessage message = new MimeMessage(session); //Identify the sender of the mail message.setFrom(new InternetAddress("15********@qq.com")); //Identify the recipient of the mail message.setRecipient(Message.RecipientType.TO, new InternetAddress("26********@qq.com")); //Title of mail message.setSubject("I am an email with pictures and attachments."); //picture MimeBodyPart body1 = new MimeBodyPart(); body1.setDataHandler(new DataHandler(new FileDataSource("src/resources/bjyx.png"))); body1.setContentID("yhbxb.png"); //Picture Setup ID //text MimeBodyPart body2 = new MimeBodyPart(); body2.setContent("Good morning<img src='cid:yhbxb.png'>","text/html;charset=utf-8"); //Enclosure MimeBodyPart body3 = new MimeBodyPart(); body3.setDataHandler(new DataHandler(new FileDataSource("src/resources/peace.properties"))); body3.setFileName("peace.properties"); MimeBodyPart body4 = new MimeBodyPart(); body4.setDataHandler(new DataHandler(new FileDataSource("src/resources/love.txt"))); body4.setFileName("love.txt"); //Stitching Pictures and Texts MimeMultipart multipart1 = new MimeMultipart(); multipart1.addBodyPart(body1); multipart1.addBodyPart(body2); multipart1.setSubType("related"); MimeBodyPart mbody = new MimeBodyPart(); mbody.setContent(multipart1); //Stitching accessories MimeMultipart multipart2 =new MimeMultipart(); multipart2.addBodyPart(body3); multipart2.addBodyPart(body4); multipart2.addBodyPart(mbody); multipart2.setSubType("mixed"); //Put it in a Message message message.setContent(multipart2); //Save Modifications message.saveChanges(); return message; } }
Sending mail in conjunction with Java Web
Write a registration page and send the user registration information to the user's e-mail.
The results are as follows.
Code
Entity class: User.java
package priv.sehun.pojo; public class User { private String username; private String password; private String email; public User() { } public User(String username, String password, String email) { this.username = username; this.password = password; this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
** Front-end Registration: ** register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <style> h1{ color: coral; align-content: center; } form{ align-content: center; } </style> </head> <body> <h1>Welcome to Pineapple Registration Page</h1> <form action="${pageContext.request.contextPath}/send" method="post"> User name:<p><input type="text" name="username" required></p> Password:<p><input type="password" name="password" required></p> Your mailbox:<p><input type="text" name="email" required></p> <input type="submit" value="register"> </form> </body> </html>
Tool class for sending mail:
package priv.sehun.utils; import priv.sehun.pojo.User; import java.util.Properties; import com.sun.mail.util.MailSSLSocketFactory; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMail extends Thread { //Website mailbox (used to send registration information to users of registered websites) private String addresserMailbox ="1597621711@qq.com"; //Mailbox username private String username = "1597621711@qq.com"; //Website Mailbox Authorization Code/Password private String addresserPassword = "lohbdcweihwvhhhb"; //Server address for sending mail private String host = "smtp.qq.com"; //User Information private User user; public SendMail(User user){ this.user = user; } @Override public void run() { try { Properties properties = new Properties(); properties.setProperty("mail.host", host); properties.setProperty("mail.transport.protocol", "smtp"); properties.setProperty("mail.smtp.auth", "true"); MailSSLSocketFactory sf = null; sf = new MailSSLSocketFactory(); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getDefaultInstance(properties, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { //Sender mail username, authorization code return new PasswordAuthentication(addresserMailbox, addresserPassword); } }); //Open Session's debug mode so that you can see the running status of the program sending Email session.setDebug(true); //Get the transport object through session Transport ts = session.getTransport(); //Connect to mail server using mailbox username and authorization code ts.connect(host, username, addresserPassword); //4. Create mail MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(addresserMailbox)); //Sender (website mailbox) message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); //Recipient (user mailbox) message.setSubject("User Registration Mail"); //Title of mail String info = "Congratulations on your successful registration^-^" +"\n Your user name is:" + user.getUsername() + "\n Your password is:" + user.getPassword() + "\n Please take good care of it.,Our website has no way to retrieve registration information"; message.setContent(info, "text/html;charset=UTF-8"); message.saveChanges(); //Send mail ts.sendMessage(message, message.getAllRecipients()); ts.close(); } catch (Exception e) { e.printStackTrace(); } } }
Corresponding Servlet: RegisterServlet.java
package priv.sehun.servlet; import priv.sehun.pojo.User; import priv.sehun.utils.SendMail; import java.io.IOException; public class RegisterServlet extends javax.servlet.http.HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { doGet(request,response); } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { try { //Receiving user requests and encapsulating them as objects String username = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); User user = new User(username,password,email); //After the user registers successfully, send an email to the user //We use threads to send mail specially to prevent time-consuming and excessive number of registered websites. SendMail send = new SendMail(user); //Start the thread, and after the thread starts, it executes the run method to send mail. send.start(); //Registered User request.setAttribute("message", "login was successful!We have sent registration information to your mailbox. Please check it carefully."); request.getRequestDispatcher("info.jsp").forward(request, response); } catch (Exception e) { e.printStackTrace(); request.setAttribute("message", "Registration failed!!"); request.getRequestDispatcher("info.jsp").forward(request, response); } } }