博客
关于我
java发送邮件工具
阅读量:806 次
发布时间:2023-01-28

本文共 2208 字,大约阅读时间需要 7 分钟。

Java 发送邮件功能实现技术文档

1. 依赖管理

在项目中导入发送邮件所需的依赖组件,以下为 Maven 项目中的坐标配置:

com.sun.mail
javax.mail
1.5.3

2. 代码实现

下面是实现发送邮件功能的具体代码,供开发者自行参考和使用:

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", "您收到验证邮件!", "邮件验证");    }}

3. 注意事项

  • 在使用时请替换为实际的邮箱地址与授权码/邮箱密码。
  • 如是QQ邮箱,需确保已开启对应的POP3/IMAP/SMTP服务,并获取相应的授权码。

转载地址:http://zsryk.baihongyu.com/

你可能感兴趣的文章
mysql中的 +号 和 CONCAT(str1,str2,...)
查看>>
Mysql中的 IFNULL 函数的详解
查看>>
mysql中的collate关键字是什么意思?
查看>>
MySql中的concat()相关函数
查看>>
mysql中的concat函数,concat_ws函数,concat_group函数之间的区别
查看>>
MySQL中的count函数
查看>>
MySQL中的DB、DBMS、SQL
查看>>
MySQL中的DECIMAL类型:MYSQL_TYPE_DECIMAL与MYSQL_TYPE_NEWDECIMAL详解
查看>>
MySQL中的GROUP_CONCAT()函数详解与实战应用
查看>>
MySQL中的IO问题分析与优化
查看>>
MySQL中的ON DUPLICATE KEY UPDATE详解与应用
查看>>
mysql中的rbs,SharePoint RBS:即使启用了RBS,内容数据库也在不断增长
查看>>
mysql中的undo log、redo log 、binlog大致概要
查看>>
Mysql中的using
查看>>
MySQL中的关键字深入比较:UNION vs UNION ALL
查看>>
mysql中的四大运算符种类汇总20多项,用了三天三夜来整理的,还不赶快收藏
查看>>
mysql中的字段如何选择合适的数据类型呢?
查看>>
MySQL中的字符集陷阱:为何避免使用UTF-8
查看>>
mysql中的数据导入与导出
查看>>
MySQL中的时间函数
查看>>