qq邮箱发送邮件工具

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

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

/**
 * qq邮箱发送邮件工具bean
 *
 * pulic 发送方法
 * 发件人邮箱
 * 授权码
 * 收件人
 * 内容
 *
 * 初始化,丢构造函数里
 */
@Component
@PropertySource(value = {"classpath:mail.properties"})
public class EmailSender {
    @Value("${mail.username}")
    private String username;
    @Value("${mail.password}")
    private String password;
    private Session session;
    public void send(String recipient, String subject, String content){
        try {
            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username)); // 设置发件人邮箱
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); // 设置收件人邮箱
            message.setSubject(subject); // 设置邮件主题
            message.setText(content); // 设置邮件内容
            // 设置邮件内容为html
            message.setContent(content,"text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功!"); // 打印成功信息
        } catch (MessagingException e) {
            e.printStackTrace(); // 打印异常堆栈信息
        }
    }

    public EmailSender() {
//        this.username = username;
//        this.password = password;
        // 设置邮件服务器属性
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.qq.com"); // 设置邮件服务器主机名
        properties.put("mail.smtp.port", "587"); // 设置邮件服务器端口号
        properties.put("mail.smtp.auth", "true"); // 启用身份验证
        properties.put("mail.smtp.starttls.enable", "true"); // 启用 TLS
        //properties.put("mail.smtp.socketFactory.port", "465"); // 设置 SSL 端口
        //properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // 设置 SSL Socket Factory
        //properties.put("mail.smtp.socketFactory.fallback", "false"); // 禁用 SSL 回退
        Authenticator authenticator = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
                // 在这里填写发送邮件的邮箱地址和密码/授权码
//                return new PasswordAuthentication(from, "your-qq-email-authorization-code"); // 使用QQ邮箱授权码进行身份验证
            }
        };
        // 创建会话对象
        session = Session.getDefaultInstance(properties,authenticator );
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

睆小白

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

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

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

打赏作者

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

抵扣说明:

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

余额充值