SoFunction
Updated on 2025-03-08

Specific examples of sending mail by Java mail

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 yourself.
My code has three classes:
The first category:

Copy the codeThe code is as follows:

package ;
/**
* Basic information required to send emails
*/
import ;
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 server
 private String userName;
 private String password;
// Is identity verification 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;  
 /**
* Obtain email session attributes
   */
 public Properties getProperties(){
   Properties p = new Properties();
   ("", );
   ("", );
   ("", validate ? "true" : "false");
   return p;
 }
 public String getMailServerHost() {
   return mailServerHost;
 }
 public void setMailServerHost(String mailServerHost) {
   = mailServerHost;
 }
 public String getMailServerPort() {
   return mailServerPort;
 }
 public void setMailServerPort(String mailServerPort) {
   = mailServerPort;
 }
 public boolean isValidate() {
   return validate;
 }
 public void setValidate(boolean validate) {
   = validate;
 }
 public String[] getAttachFileNames() {
   return attachFileNames;
 }
 public void setAttachFileNames(String[] fileNames) {
   = fileNames;
 }
 public String getFromAddress() {
   return fromAddress;
 }
 public void setFromAddress(String fromAddress) {
   = fromAddress;
 }
 public String getPassword() {
   return password;
 }
 public void setPassword(String password) {
   = password;
 }
 public String getToAddress() {
   return toAddress;
 }
 public void setToAddress(String toAddress) {
   = toAddress;
 }
 public String getUserName() {
   return userName;
 }
 public void setUserName(String userName) {
   = userName;
 }
 public String getSubject() {
   return subject;
 }
 public void setSubject(String subject) {
   = subject;
 }
 public String getContent() {
   return content;
 }
 public void setContent(String textContent) {
   = textContent;
 }
}

The second class:

Copy the codeThe code is as follows:

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

/**
* 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 = ();
   if (()) {
// If identity authentication is required, create a password authenticator
  authenticator = new MyAuthenticator((), ());
   }
// Construct a session to send emails based on the email session properties and password validator
   Session sendMailSession = (pro,authenticator);
   try {
// Create an email message based on the session
   Message mailMessage = new MimeMessage(sendMailSession);
// Create the email sender address
   Address from = new InternetAddress(());
// Set the sender of the email message
   (from);
// Create the recipient address of the email and set it to the email message
   Address to = new InternetAddress(());
   (,to);
// Set the subject of the email message
   (());
// Set the time for sending email messages
   (new Date());
// Set the main content of the email message
   String mailContent = ();
   (mailContent);
// Send email
   (mailMessage);
   return true;
   } catch (MessagingException ex) {
    ();
   }
   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 = ();
//If identity authentication is required, create a password authenticator
   if (()) {
  authenticator = new MyAuthenticator((), ());
   }
// Construct a session to send emails based on the email session properties and password validator
   Session sendMailSession = (pro,authenticator);
   try {
// Create an email message based on the session
   Message mailMessage = new MimeMessage(sendMailSession);
// Create the email sender address
   Address from = new InternetAddress(());
// Set the sender of the email message
   (from);
// Create the recipient address of the email and set it to the email message
   Address to = new InternetAddress(());
// The attribute indicates that the type of the receiver is TO
   (,to);
// Set the subject of the email message
   (());
// Set the time for sending email messages
   (new Date());
// The 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
   ((), "text/html; charset=utf-8");
   (html);
// Set the MiniMultipart object to the mail content
   (mainPart);
// Send email
   (mailMessage);
   return true;
   } catch (MessagingException ex) {
    ();
   }
   return false;
 }
}

The third category:

Copy the codeThe code is as follows:

package ;

import .*;

public class MyAuthenticator extends Authenticator{
 String userName=null;
 String password=null;

 public MyAuthenticator(){
 }
 public MyAuthenticator(String username, String password) {
   = username;
   = password;
 }
 protected PasswordAuthentication getPasswordAuthentication(){
  return new PasswordAuthentication(userName, password);
 }
}

The following is the code using the above three classes:

Copy the codeThe code is as follows:

public static void main(String[] args){
//This class mainly sets up emails
   MailSenderInfo mailInfo = new MailSenderInfo();
   ("smtp.");
   ("25");
   (true);
   ("han2000lei@");
("*********");//Your email password
   ("han2000lei@");
   ("han2000lei@");
("Set the email title");
("Set the mailbox content");
//This class mainly sends emails
   SimpleMailSender sms = new SimpleMailSender();
(mailInfo);//Send text format
(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 use packages for these three classes. If you don’t like them, you can change them 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 is just registered, then you should not use "smtp." 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 question is the two sentences ("smtp."); and ("han2000lei@"); 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.