Implementation of java mail delivery

  • 2020-05-10 18:13:33
  • OfStack

Email is in daily life. This article mainly introduces the method of java sending emails based on SMTP, and analyzes the relevant skills of java sending emails based on SMTP. It has a definite reference value, and friends in need can refer to it.

1. Write an MailSendProper class to encapsulate the required properties


import java.util.Properties;
public class MailSendProper {
    private String Host ;          // Of the mail server ip
    private String Port ;          // The port number of the sending mail server 
    private String SendAddress ;      // The address of the sender 
    private String ReceiveAddress ;     // The recipient's address 
    private String username ;        // Login to the user name of the sending mailbox 
    private String password ;        // Password to log in and send email 
    private boolean isvalidate = true ;   // Whether authentication is required 
    private String subject ;        // Email title 
    private String content ;       // Email content 

    public String getSubject() {
      return subject;
    }
    public void setSubject(String subject) {
      this.subject = subject;
    }
    public String getContent() {
      return content;
    }
    public void setContent(String content) {
      this.content = content;
    }
    public String getHost() {
      return Host;
    }
    public void setHost(String host) {
      Host = host;
    }
    public String getPort() {
      return Port;
    }
    public void setPort(String port) {
      Port = port;
    }
    public String getSendAddress() {
      return SendAddress;
    }
    public void setSendAddress(String sendAddress) {
      SendAddress = sendAddress;
    }
    public String getReceiveAddress() {
      return ReceiveAddress;
    }
    public void setReceiveAddress(String receiveAddress) {
      ReceiveAddress = receiveAddress;
    }
    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 boolean isIsvalidate() {
      return isvalidate;
    }
    public void setIsvalidate(boolean isvalidate) {
      this.isvalidate = isvalidate;
    }
    public Properties getProperties(){
      Properties properties = new Properties() ;
      properties.put("mail.smtp.host", this.Host) ;
      properties.put("mail.smtp.port", this.Port) ;
      properties.put("mail.smtp.auth", isvalidate?"true":"false") ;
      return properties ;
    }
}

2. Write an   EmailMessage package to send information


public class EmailMessage {
    private String title ;
    private String context ;
    private String toEmail ;

    public EmailMessage() {
      super();
    }
    public EmailMessage(String title, String context, String toEmail) {
      super();
      this.title = title;
      this.context = context;
      this.toEmail = toEmail;
    }
    public String getTitle() {
      return title;
    }
    public void setTitle(String title) {
      this.title = title;
    }
    public String getContext() {
      return context;
    }
    public void setContext(String context) {
      this.context = context;
    }
    public String getToEmail() {
      return toEmail;
    }
    public void setToEmail(String toEmail) {
      this.toEmail = toEmail;
    }
}

3. Write an MailAttorney   email password validator class


import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MailAttorney extends Authenticator {
  private String username ;
  private String password ;

  public MailAttorney(String username,String password) {
    this.username = username ;
    this.password = password ;
  }
  // Override the parent method to get the password authenticator 
  @Override
  protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(username,password) ;
  }
}

4. Write an MailSend   email tool class


import java.util.Date;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.VTBBS.entity.EmailMessage;

public class MailSend {
    public static boolean mailTest(MailSendProper mailsender){
        MailAttorney attorney = null ;
        if(mailsender.isIsvalidate()){// Determine if identification is required 
          attorney = new MailAttorney(mailsender.getUsername(),mailsender.getPassword()) ;
        }
        // Constructed from mailbox session properties and password validators 1 It's sending emails seesion
        Session session = Session.getInstance(mailsender.getProperties(),attorney) ;
        // According to the session create 1 Email messages 
        Message mailMessage = new MimeMessage(session) ;
        try {
          // Create the email sender's address 
          Address from = new InternetAddress(mailsender.getSendAddress()) ;
          // Set the sender of the mailbox message 
          mailMessage.setFrom(from);
          // Create the address to receive this message and set it to the mail message 
          Address to = new InternetAddress(mailsender.getReceiveAddress()) ;
          mailMessage.setRecipient(Message.RecipientType.TO, to);
          mailMessage.setSubject(mailsender.getSubject()); // Set the subject line 
          mailMessage.setSentDate(new Date()); // Set the time to send the email 
          mailMessage.setText(mailsender.getContent()); // Set email content 
          Transport.send(mailMessage);
          return true ;
        } catch (Exception e) {
          e.printStackTrace();
          return false ;
        }
    }

    public static boolean sendEmail(EmailMessage message){
        MailSendProper mail = new MailSendProper() ;
        mail.setHost("smtp.126.com");          //smtp Simple mail transfer protocol, the default port number is 25 . 
        mail.setPort("25");
        mail.setIsvalidate(true);              // Authentication is required 
        mail.setUsername("");               // Set the login username  
        mail.setPassword("");               // Set the sender's password 
        mail.setSendAddress("");             // Set the address to send this   The sender's address is the same as the login username 1 a 
        mail.setReceiveAddress(message.getToEmail());  // Set the address of the receiver 
        mail.setSubject(message.getTitle());        // Set the mailbox title 
        mail.setContent(message.getContext());      // Set the contents of the mailbox 
        return mailTest(mail) ;
    }

}

Note: the used mailbox must have the POP3/SMTP service enabled to send successfully. Different mailboxes have different transport protocols, such as:

QQ mailbox: SMTP transport protocol is smtp.qq.com port 25

The POP3 transport protocol is pop3.qq.com   port 110

5. Use method test


public static void main(String[] args) {
  EmailMessage message = new EmailMessage() ;
  String code = String.valueOf(Math.random()).substring(3, 9) ; // Generate verification code 
  message.setTitle(" Email address verification ");                  // Email title 
  message.setContext(" Dear users, your captcha code is "+code+" . "); // Email content 
  message.setToEmail("940202884@qq.com"); // Who to send it to 
  System.out.println(MailSend.sendEmail(message)?" Send a success ":" Send failure ") ;
}

I hope this article is helpful for you to learn java programming.


Related articles: