java for Sending Mail

  • 2021-06-28 12:35:30
  • OfStack

Preface

In the past few days, do an urgent function, some of which require email notification;By consulting and experimenting, I quickly wrote a function to send mail.Now sort out 1 record.

Send Mail

1. Introducing dependencies in pom


 <dependency>
   <groupId>javax.mail</groupId>
   <artifactId>javax.mail-api</artifactId>
   <version>1.5.6</version>
</dependency>
 
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-email</artifactId>
   <version>1.4</version>
</dependency>

2. Tool class for sending mail


package com.zhanghan;
 
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
 
import java.util.ArrayList;
import java.util.List;
 
@Service
public class EmailServiceImpl implements EmailService {
  @Override
  public void sendMail(String address, String subject, String htmlMsg, Boolean isSSL) throws EmailException {
 
    if (StringUtils.isEmpty(address) || StringUtils.isEmpty(subject) || StringUtils.isEmpty(htmlMsg)) {
      throw new EmailException();
    }
 
    try {
      HtmlEmail email = new HtmlEmail();
      List<String> list = new ArrayList<String>();
      list.add(address);
      String[] tos = list.toArray(new String[list.size()]);
 
      //  Here is SMTP Name of the sending server: 163 These are as follows: "smtp.163.com"
      email.setHostName("smtp.exmail.qq.com");
      if (isSSL) {
        email.setSSLOnConnect(true);
        email.setSmtpPort(465);
      }
      //  Settings for character encoding sets 
      email.setCharset("UTF-8");
      //  Recipient's mailbox 
      email.addTo(tos);
      //  Sender's mailbox and sender name 
      email.setFrom("XXX@163.com", "zhanghan");
      //  If authentication information is required, set authentication: user name - Password.Registered name and password for sender on mail server 
      email.setAuthentication("XXX@163.com", "yyyy");
      //  Subject of the message to be sent 
      email.setSubject(subject);
      //  The message to be sent is due to the use of HtmlEmail , which can be used in mail content HTML Label 
      email.setHtmlMsg(htmlMsg);
 
      String result1 = email.send();      
 
    } catch (Exception e) {
      e.printStackTrace();
      throw new EmailException();
    }
  }
}

3. pits encountered

There is no problem testing locally;Our test service is on Ali Yun, Ali Yun failed when sending the pair;The trace log found that AliYun would close the default port 25 for sending mail.The port needs to be changed to 465.

summary

1. When you encounter problems, you should read more logs and track down problems.

2. Keep accumulating and improving your knowledge system.


Related articles: