preface
E-mail is widely used, such as registering an account on a website and automatically sending an activation e-mail; Retrieve the password by email; Send activity information, etc. Obviously, these processes can not be operated manually (open browser, open mailbox, create email and send email), so they can only realize the function of sending email through diligent programs~
Maybe some friends don't know how to realize the function of sending e-mail. Let's talk about how to use code to send e-mail.
Mail sending
Sending e-mail needs to comply with specific protocols. Common E-mail protocols include SMTP, POP3 and IMAP. Among them, the creation and sending of e-mail only need to use SMTP protocol (Simple Mail Transfer Protocol). Let's take mailbox 163 as an example.
Turn on SMTP service
If you need to send mail, you need to make preparations, that is, open the SMTP service of the mailbox.
First log in to mailbox 163, click the setting button above, and then click "POP3/SMTP/IMAP" to enter the setting page and start the SMTP service
After opening the SMTP service, an authorization code will be generated. Don't forget the authorization code. It will be used later~
Emerald flower! Upper code
The SMTP service of the mailbox has been started, and the next step is the code.
First, Maven dependency is introduced
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
Before sending an email, let's create a simple email file to see what it looks like 🧐
import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Date; import java.util.Properties; /** * Create a simple message * @description: MailTest * @author: Zhuang ba.liziye * @create: 2021-11-23 14:44 **/ public class CreatMail { public static void main(String[] args) throws Exception { //Create message Properties props = new Properties(); // Parameter configuration for connecting to mail server Session session= Session.getInstance(props); // Create a session object according to the parameter configuration MimeMessage message = new MimeMessage(session); // Create mail object /* * You can also read the local eml and create a MimeMessage object * new MimeMessage(session, new FileInputStream("D://email//test.eml")); */ // From: sender // The three parameters of Internet address are: sender's mailbox, displayed nickname (only for display, no special requirements), and character set code of nickname message.setFrom(new InternetAddress("XXXXXX", "Refused to cross Jiangdong", "UTF-8")); // To: recipient message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("XXXXXX", "USER_CC", "UTF-8")); // To: add recipients (optional) //message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress("xxxx@xxxx.com", "USER_DD", "UTF-8")); // Cc: Cc (optional) //message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress("xxxx@xxxx.com", "USER_EE", "UTF-8")); // Bcc: Bcc (optional) //message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress("xxxx@xxxx.com", "USER_FF", "UTF-8")); // Subject: mail subject message.setSubject("Test mail sending", "UTF-8"); // Content: message body (html tags can be used) message.setContent("I was eating fried chicken in the people's Square", "text/html;charset=UTF-8"); // Set the outgoing time displayed message.setSentDate(new Date()); // Save previous settings message.saveChanges(); // Save this message locally OutputStream out = new FileOutputStream("D:\\email\\test.eml"); message.writeTo(out); out.flush(); out.close(); } }
We can take a look at the created test.eml file, which contains the text in SMTP protocol format (encoded with base64), where from: user_ The content after AA is the sender's mailbox, to: user_ The content after CC is the recipient's mailbox.
Next, let's get to the point and see how to send mail in code (● '◡' ●)
import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties; /** * @program: Send mail * @description: SendMail * @author: Zhuang ba.liziye * @create: 2021-11-23 14:57 **/ public class SendMail { public static String myEmailAccount = "xxxxxx@163.com"; //Sender mailbox public static String myEmailPassword = "XXXXXX"; //SMTP service authorization code (just mentioned above ~ don't forget ~) // SMTP server address of the sender's mailbox, public static String myEmailSMTPHost = "smtp.163.com"; // Recipient mailbox public static String receiveMailAccount = "xxxxx@qq.com"; public static void main(String[] args) throws Exception { // Parameter configuration Properties props = new Properties(); // Parameter configuration props.setProperty("mail.transport.protocol", "smtp"); // Protocol used (JavaMail specification requirements) props.setProperty("mail.smtp.host", myEmailSMTPHost); // SMTP server address of sender's mailbox props.setProperty("mail.smtp.auth", "true"); // Require authentication // Create a session object according to the configuration to interact with the mail server Session session = Session.getInstance(props); // Set the debug mode to view the detailed sending log session.setDebug(true); // Create a message MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount); // Get mail transfer object according to Session Transport transport = session.getTransport(); // Sender's mailbox and authorization code after opening SMTP service transport.connect(myEmailAccount, myEmailPassword); // Send mail to all recipient addresses. message.getAllRecipients() gets the recipients, CC and BCC added when creating the mail object transport.sendMessage(message, message.getAllRecipients()); // Close connection transport.close(); } /** * Create a simple message * * @param session Session interacting with the server * @param sendMailAddress Sender email address * @param receiveMailAddress Recipient email address * @return * @throws Exception */ public static MimeMessage createMimeMessage(Session session, String sendMailAddress, String receiveMailAddress) throws Exception { // Create a message MimeMessage message = new MimeMessage(session); // From: sender message.setFrom(new InternetAddress(sendMailAddress, "Refused to cross Jiangdong", "UTF-8")); // To: recipient (multiple recipients, CC, BCC can be added) message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMailAddress, "Tester", "UTF-8")); // Subject: mail subject message.setSubject("Eat fried chicken", "UTF-8"); // Content: message body (html tags can be used) message.setContent("I was eating fried chicken in the people's Square", "text/html;charset=UTF-8"); // Set sending time message.setSentDate(new Date()); // Save settings message.saveChanges(); return message; } }
Note here:
Some mailbox servers require SMTP connections to use SSL security authentication (such as QQ mailbox), so you need to add several parameters to the parameter configuration, such as 👇 As shown in (for SMTP port, different mailbox ports are different, and the specific port number needs to be queried by yourself; if SSL security authentication is not used, the connection port does not need to be specified, which is generally 25 by default)
final String smtpPort = "xxx"; props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort);
P.S. myEmailPassword refers to the authorization code of SMTP service. Don't write it as the password of email~
Execute the above code to see what the effect is~
After executing the code, the console will output a log, including a sentence DEBUG SMTP: connected to host "smtp.163.com", port: 25, which proves the above sentence: if SSL security authentication is not used, the connection port does not need to be specified. Generally, the default is 25 O(∩ ∩) O
Summary
My experience is limited, and some places may not be particularly good. If you think of any problems when reading, please leave a message in the comment area, and we will discuss it later 🙇
If there are errors in the article, you are welcome to leave a message for correction; If you have a better and more original understanding, you are welcome to leave your valuable ideas in the message area.
When you are hit, remember your precious and resist malice;
When you are confused, believe in your precious and put aside gossip;
Love what you love, do what you do, listen to your heart and ask nothing