本文共 2208 字,大约阅读时间需要 7 分钟。
在项目中导入发送邮件所需的依赖组件,以下为 Maven 项目中的坐标配置:
com.sun.mail javax.mail 1.5.3
下面是实现发送邮件功能的具体代码,供开发者自行参考和使用:
package com.hnyyjsxy.util;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import java.util.Properties;public final class MailUtils { private static final String USER = "XXXXXXXXXX@qq.com"; // 发件人邮箱地址 private static final String PASSWORD = "XXXXXXXX"; //QQ邮箱授权码或邮箱密码 /** * 发送邮件功能工具类 * @param to 收件人邮箱 * @param text 邮件正文内容 * @param title 邮件标题 */ public static boolean sendMail(String to, String text, String title) { try { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", "smtp.qq.com"); props.put("mail.user", USER); props.put("mail.password", PASSWORD); Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { String userName = props.getProperty("mail.user"); String password = props.getProperty("mail.password"); return new PasswordAuthentication(userName, password); } }; Session mailSession = Session.getInstance(props, authenticator); MimeMessage message = new MimeMessage(mailSession); InternetAddress form = new InternetAddress(USER); message.setFrom(form); InternetAddress toAddress = new InternetAddress(to); message.setRecipient(Message.RecipientType.TO, toAddress); message.setSubject(title); message.setContent(text, "text/html;charset=UTF-8"); Transport.send(message); return true; } catch (Exception e) { e.printStackTrace(); } return false; } public static void main(String[] args) throws Exception { // 测试用例示例 MailUtils.sendMail("XXXX@qq.com", "您收到验证邮件!", "邮件验证"); }}
转载地址:http://zsryk.baihongyu.com/