Java网易163邮箱工具类-部署到Linux

1,设置163邮箱

开启POP3/SMTP/IMAP

2,依赖

<dependency>
	<groupId>jakarta.mail</groupId>
	<artifactId>jakarta.mail-api</artifactId>
	<version>2.1.3</version>
</dependency>
<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>jakarta.mail</artifactId>
	<version>2.0.1</version>
</dependency>

3,MailUtil

package com.xxx.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MailUtil {
    /**
     * 发件人邮箱
     */
    private static final String SENDER_ACCOUNT = "xxxxx@163.com";
    /**
     * 邮箱密码/授权码
     */
    private static final String AUTH_CODE = "xxxxxxxx";

    /**
     * 发送邮件
     *
     * @param direction 收件人邮箱地址
     * @param subject   邮件名称/标题
     * @param message   消息、内容
     */
    public static boolean sendMail(String direction, String subject, String message) {
        Properties props = new Properties();
        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.163.com");
        // 使用SSL,端口号994
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        try {
            // 创建有指定属性的session
            Session session = Session.getInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(SENDER_ACCOUNT, AUTH_CODE);
                }
            });

            // 新建消息
            Message msg = new MimeMessage(session);
            msg.setSubject(subject);
            msg.setText(message);
            msg.setFrom(new InternetAddress(SENDER_ACCOUNT));
            Transport transport = session.getTransport("smtp");
            transport.connect();
            transport.sendMessage(msg, new InternetAddress[]{new InternetAddress(direction)});
            transport.close();
            return true;
        } catch (NoSuchProviderException e) {
            System.out.println("没有找到邮件服务提供者: " + e.getMessage());
        } catch (MessagingException e) {
            System.out.println("邮件发送过程中出现异常: " + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }
}

4,注意

端口:
SSL加密:接收服务器(IMAP)端口号为993,发送服务器(SMTP)端口号为465。
阿里屏蔽了25端口,只能用465发送邮件,否则本地测试正常,上线阿里云服务器后失败。

posted @ 2024-06-21 12:27  Rix里克斯  阅读(344)  评论(0)    收藏  举报