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发送邮件,否则本地测试正常,上线阿里云服务器后失败。
本文作者:Ritchie里其
本文链接:https://www.cnblogs.com/wang-zeyu/p/18260283
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步