【JavaEmail】Send email

need:

每月1日发送邮件,使用JavaEmail实现

Common email protocols include:

SMTP: Simple Mail Transfer Protocol, a transport protocol used for sending email. (Default port 25), communication rules between mail client and SMTP mail server.
POP/POP3: Standard protocol for receiving email. (Default port 110), downloads emails stored in the POP protocol mail server to the user's computer, but cannot perform online operations on the emails.
IMAP: Internet Message Access Protocol, a replacement for POP3. (Default port 143), you can directly operate the mail on the server online through the client.
These three protocols have corresponding SSL encrypted transmission protocols, namely SMTPS, POP3S and IMAPS.

Key objects of JavaMail:

1. Properties

Attributes type illustrate
mail.smtp.host string smtp server address
mail.smtp.port int smtp server port, default 25
mail.smtp.auth boolean Whether the smtp server requires user authentication, default false
mail.smtp.user string smtp default login username
mail.smtp.from string Default email sending source address
mail.smtp.socketFactory.class String Must implement javax.net.SocketFactory interface
mail.smtp.socketFactory.port int Specify the port number used by the socket factory class
mail.smtp.socketFactory.fallback boolean When set to true, when the socket creation using the specified socket class fails, the socket will be created using java.net.Socket. The default is true.
mail.smtp.timeout int Connection timeout, unit is ms, default is never timeout

2.Session: Session object, which is a collection of configuration information.
3.Transport and Store: transmission and storage.

pom dependencies:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.6.0</version>
</dependency>

As a result, the following error was reported when the local test was started:
java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
Reason:
MailLogger -- is part of JavaMail and is included in the Java EE environment, but not included in the Java SE environment. The main reason for this error is to test email sending in the SE environment;
javax.mail-api is only suitable for compilation, but if you really want to run the code, you must fully implement JavaMail
and modify the pom dependency:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>

Related links: https://blog.csdn.net/shijiujiu33/article/details/89490227Pom
dependencies for online production environment:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.5</version >
</dependency>
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.5.4</version>
</dependency>

send email:

1. Packaging tools

Before sending an email, a Session connection will be created every time. Here you can define a JavaMailUtils tool class. Every time you create a connection, you only need to call the createSession() method, so you don't have to write repeated code frequently. (You can encapsulate it or not depending on your business needs)

@Component
public class JavaEmailUtils {
    
    

    /**
     * 创建Session连接
     * @return
     */
    public static Session createSession() {
    
    
        //服务器地址
        String smtp ="smtp.163.com";
        //发件人的邮箱
        String userName = "[email protected]";
        //发件人密码 | 授权码
        String password = "xxxxxxx";
        //SSL链接端口
        String emailPort = "465";

        Properties props = new Properties();
        // 是否打开验证:只能设置true,必须打开
        props.setProperty("mail.smtp.auth", "true");
        //stmp协议
        props.setProperty("mail.transport.protocol", "smtp");
        // 使用JSSE的SSL
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        // 只处理SSL的连接,对于非SSL的连接不做处理
        props.put("mail.smtp.socketFactory.fallback", "false");
        // smtp服务器地址
        props.put("mail.smtp.host", smtp);
        props.put("mail.smtp.port",emailPort);
        props.put("mail.smtp.socketFactory.port", emailPort);
        props.put("mail.smtp.ssl.enable", true);
        props.put("mail.smtp.starttls.enable","true");


        Session session = Session.getInstance(props, new Authenticator() {
    
    

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
    
    
                // TODO Auto-generated method stub
                return new PasswordAuthentication(userName, password);
            }

        });

        session.setDebug(true);

        return session;
    }

}

Reference link for packaging tools: https://blog.csdn.net/weixin_48349878/article/details/125832568
NetEase mailbox reference link for obtaining the authorization code: https://blog.csdn.net/weixin_45752540/article/details/120684315

2. Create emails (send emails without using packaging tools)

public ResultVO sendFjEmail(GsbSendEmail gsbSendEmail, String emailAccounts, String emailAuthorizationCode, String emailPort, String title, String content) {
    
    
        try {
    
    
            // 1. 创建一封邮件
            Properties props = new Properties();
            // 是否打开验证:只能设置true,必须打开
            props.setProperty("mail.smtp.auth", "true");
            //stmp协议
            props.setProperty("mail.transport.protocol", "smtp");
            //smtp协议
            String smtp = "smtp.163.com";

            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");// 使用JSSE的SSL
            props.put("mail.smtp.socketFactory.fallback", "false");  // 只处理SSL的连接,对于非SSL的连接不做处理
            // 设置主机地址 smtp.qq.com smtp.126.com smtp.163.com
            props.put("mail.smtp.port", emailPort);
            props.put("mail.smtp.socketFactory.port", emailPort);
            props.put("mail.smtp.ssl.enable", true);
            props.put("mail.smtp.host", smtp);// smtp服务器地址

            // 用于连接邮件服务器的参数配置(发送邮件时才需要用到)
            // 根据参数配置,创建会话对象(为了发送邮件准备的)
            Session session = Session.getInstance(props);
            session.setDebug(true);

            //创建邮件对象
            Message msg = new MimeMessage(session);
            //Subject: 邮件主题
            msg.setSubject(title);
            //发件人邮箱(我的163邮箱)
            msg.setFrom(new InternetAddress(emailAccounts));
            //收件人邮箱(我的网易云邮箱) 可增加收件人邮箱
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(“邮箱”));

            //创建附件“节点”
            MimeBodyPart attachment = new MimeBodyPart();
            // 读取本地文件
            // 模板地址
            String filePath = "src" + File.separator + "main" + File.separator + "resources" + File.separator + "template" + File.separator + "xxx.docx";
            DataHandler dh2 = new DataHandler(new FileDataSource(filePath));
            // 将附件数据添加到“节点”
            attachment.setDataHandler(dh2);
            // 设置附件的文件名(需要编码)
            attachment.setFileName(MimeUtility.encodeText(dh2.getName()));

            //正文 将文本封装成一个节点
            MimeBodyPart body = new MimeBodyPart();
            body.setContent(content, "text/html;charset=utf-8");

            //设置文本和附件的关系
            Multipart msgPart = new MimeMultipart();
            msgPart.addBodyPart(body);
//            msgPart.addBodyPart(attachment);

            //Content: 邮件正文(可以使用html标签)设置整个邮件的关系(将最终的混合“节点”作为邮件的内容添加到邮件对象)
            msg.setContent(msgPart);

            //保存前面的设置(邮件生成的最后一步)
            msg.saveChanges();

            Transport transport = session.getTransport();
            transport.connect(emailAccounts, emailAuthorizationCode);//发件人邮箱,授权码(可以在邮箱设置中获取到授权码的信息)
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

            //todo 邮件发送成功,记录日志信息
            setLogger(gsbSendEmail,"1","邮件发送成功!");
            return new ResultVO().addData("data", "OK");
        } catch (Exception e) {
    
    
            // TODO: 邮件发送失败,记录日志信息
            setLogger(gsbSendEmail,"0",e.toString());
            return new ResultVO("发送邮箱失败!请联系管理员进行排查");
        }
    }

Email verification rules:

Verification logic that needs to be met:

  1. There must be content before @ and it can only be letters (uppercase and lowercase), numbers, underscores (_), minus signs (-), and dots (.)
  2. There must be content between @ and the last dot (.) and it can only be letters (upper and lower case), numbers, dots (.), and minus signs (-), and the two dots cannot be next to each other.
  3. There must be content after the last dot (.) and the content can only be letters (upper and lower case), numbers, and the length is greater than or equal to 2 bytes and less than or equal to 6 bytes.

Regular expression for email verification:

^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{
    
    2,6}$

Guess you like

Origin blog.csdn.net/m0_46459413/article/details/128545058