Java 发送邮件

导入坐标

<!-- 邮件 -->
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

代码实现

import org.junit.jupiter.api.Test;

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

public class RunTests {
    // 发送邮件测试
    @Test
    public void testEmail() {
        String host = "smtp.qq.com";           // SMTP 服务器信息
        final String username = "xxx@qq.com";  // 你的邮件地址
        final String password = "xxxxxx";      // 你的邮件密码
        String to = "xxx@qq.com";              // 收件人邮箱

        // 设置邮件服务器属性
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", "587");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true"); // 启用 STARTTLS 加密

        // 创建会话并验证身份
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // 创建邮件对象
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));                             // 设置发件人
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // 设置收件人
            message.setSubject("标题内容");                                              // 设置邮件标题
            message.setText("发送的内容");                                               // 设置邮件正文

            // 发送邮件
            Transport.send(message);

            System.out.println("邮件发送成功!");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FatCat-BOY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值