I learned about JavaMail today. Sending emails in javamail is indeed a relatively troublesome issue. For the convenience of future use, I wrote a piece of code myself and typed it into a jar package for the convenience of future use. hehe
The following three codes are all my code. If you want to use them, just copy them directly. Because I don’t know how to upload the jar package to javaeye, friends go back and make it by themselves.
My code has three classes:
The first class: MailSenderInfo.java
The code copy is as follows:
package com.util.mail;
/**
* Basic information required to send emails
*/
import java.util.Properties;
public class MailSenderInfo {
// The IP and port of the server that sends the mail
private String mailServerHost;
private String mailServerPort = "25";
// The address of the sender of the email
private String fromAddress;
// The address of the email recipient
private String toAddress;
// Log in to the username and password of the email sending server
private String userName;
private String password;
// Is authentication required
private boolean validate = false;
// Email Subject
private String subject;
// The text content of the email
private String content;
// File name of the email attachment
private String[] attachFileNames;
/**
* Get email session attributes
*/
public Properties getProperties(){
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
this.mailServerPort = mailServerPort;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] fileNames) {
this.attachFileNames = fileNames;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String textContent) {
this.content = textContent;
}
}
The second class: SimpleMailSender.java
The code copy is as follows:
package com.util.mail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
* Simple mail (mail without attachments) sender
*/
public class SimpleMailSender {
/**
* Send emails in text format
* @param mailInfo Information about the email to be sent
*/
public boolean sendTextMail(MailSenderInfo mailInfo) {
// Determine whether identity authentication is required
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// If identity authentication is required, create a password authenticator
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// Construct a session to send emails based on the email session properties and password validator
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// Create a mail message based on the session
Message mailMessage = new MimeMessage(sendMailSession);
// Create the email sender address
Address from = new InternetAddress(mailInfo.getFromAddress());
// Set the sender of the email message
mailMessage.setFrom(from);
// Create the recipient address of the email and set it to the email message
Address to = new InternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO,to);
// Set the subject of the email message
mailMessage.setSubject(mailInfo.getSubject());
// Set the time for sending email messages
mailMessage.setSentDate(new Date());
// Set the main content of the email message
String mailContent = mailInfo.getContent();
mailMessage.setText(mailContent);
// Send email
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
/**
* Send emails in HTML format
* @param mailInfo mail information to be sent
*/
public static boolean sendHtmlMail(MailSenderInfo mailInfo){
// Determine whether identity authentication is required
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
// If identity authentication is required, create a password authenticator
if (mailInfo.isValidate()) {
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// Construct a session to send emails based on the email session properties and password validator
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// Create a mail message based on the session
Message mailMessage = new MimeMessage(sendMailSession);
// Create the email sender address
Address from = new InternetAddress(mailInfo.getFromAddress());
// Set the sender of the email message
mailMessage.setFrom(from);
// Create the recipient address of the email and set it to the email message
Address to = new InternetAddress(mailInfo.getToAddress());
// Message.RecipientType.TO attribute indicates that the receiver's type is TO
mailMessage.setRecipient(Message.RecipientType.TO,to);
// Set the subject of the email message
mailMessage.setSubject(mailInfo.getSubject());
// Set the time for sending email messages
mailMessage.setSentDate(new Date());
// MiniMultipart class is a container class that contains objects of type MimeBodyPart
Multipart mainPart = new MimeMultipart();
// Create a MimeBodyPart containing HTML content
BodyPart html = new MimeBodyPart();
// Set HTML content
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// Set MiniMultipart object to mail content
mailMessage.setContent(mainPart);
// Send mail
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
}
The third category: MyAuthenticator.java
The code copy is as follows:
package com.util.mail;
import javax.mail.*;
public class MyAuthenticator extends Authenticator{
String userName=null;
String password=null;
public MyAuthenticator(){
}
public MyAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
The following is the code using the above three classes:
The code copy is as follows:
public static void main(String[] args){
//This class mainly sets up email
MailSenderInfo mailInfo = new MailSenderInfo();
mailInfo.setMailServerHost("smtp.163.com");
mailInfo.setMailServerPort("25");
mailInfo.setValidate(true);
mailInfo.setUserName("[email protected]");
mailInfo.setPassword("*********");//Your email password
mailInfo.setFromAddress("[email protected]");
mailInfo.setToAddress("[email protected]");
mailInfo.setSubject("Set mailbox title");
mailInfo.setContent("Set mailbox content");
//This class mainly sends emails
SimpleMailSender sms = new SimpleMailSender();
sms.sendTextMail(mailInfo);//Send text format
sms.sendHtmlMail(mailInfo);//Send html format
}
Finally, let me give you some attention to:
1. Using this code, you can complete the email sending function of your javamail. All three categories are indispensable.
2. I used the com.util.mail package to package these three classes. If you don't like it, you can change it yourself, but the three class files must be in the same package.
3. Do not use the email address you have just registered to send emails in the program. If your 163 email address has just been registered, then you should not use "smtp.163.com". Because you can't send it out. The email address you just registered will not give you such permissions, which means you cannot pass the verification. You need to use the email address you use frequently, and it takes a long time.
4. Another problem is the two sentences of mailInfo.setMailServerHost("smtp.163.com"); and mailInfo.setFromAddress("[email protected]"); That is, if you use the 163smtp server, then you must use the 163 email address to send the email address. If you don’t, the sending will not be successful.
5. There are many explanations on the Internet about javamail verification errors, but I only see one. It's my third category. As long as you copy all the code, I think there will be no problem.