package com.ruoyi.common.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮箱发送工具类
 */
@Component
@RequiredArgsConstructor  // Lombok自动注入依赖
public class EmailUtils {

    private final JavaMailSender javaMailSender;  // Spring Boot自动配置的邮件发送器

    @Value("${spring.mail.username}")
    private String username;


    /**
     * 发送纯文本邮件
     * @param to 收件人邮箱
     * @param subject 邮件主题
     * @param content 邮件内容
     * @throws MessagingException 邮件发送异常
     */
    public void sendTextEmail(String to, String subject, String content) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setFrom(username);  // 发件人邮箱（需与配置文件中username一致）
        helper.setTo(to);  // 收件人邮箱
        helper.setSubject(subject);  // 邮件主题
        helper.setText(content, false);  // 第二个参数：false=纯文本，true=HTML
        javaMailSender.send(message);
    }

    /**
     * 发送HTML格式邮件（可选，支持富文本）
     * @param to 收件人邮箱
     * @param subject 邮件主题
     * @param htmlContent HTML内容
     * @throws MessagingException 邮件发送异常
     */
    public void sendHtmlEmail(String to, String subject, String htmlContent) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setFrom("your_qq_email@qq.com");
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true);  // 第二个参数：true=HTML格式
        javaMailSender.send(message);
    }
}
