这里基于Hutools开发,实际业务中可以切换为原生的Spring Mail类
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.cosmoplat.tyre.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
* @author guoxiang
* @version 1.0.0
* @since 2022/2/8
*/
@Component
@Slf4j
public class MailUtils implements ApplicationContextAware {
private static final MailAccount ACCOUNT = new MailAccount();
/**
* 发送邮件
*
* @param to 收件人
* @param title 标题
* @param content 内容
*/
public static void send(String to, String title, String content) {
try {
MailUtil.send(ACCOUNT, to, title, content, false);
} catch (Exception e) {
log.error("发送邮件失败", e);
throw new BaseException("发送邮件失败");
}
}
/**
* 初始化
*
* @param applicationContext 上下文
* @throws BeansException 异常
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Environment environment = applicationContext.getEnvironment();
String host = environment.getProperty("email.host", "smtp.163.com");
Integer port = Integer.valueOf(environment.getProperty("email.port", "25"));
String user = environment.getProperty("email.user", "xxxxxx@163.com");
String pass = environment.getProperty("email.pass", "邮箱授权码");
ACCOUNT.setHost(host)
.setPort(port)
.setAuth(true)
.setFrom(user)
.setUser(user)
.setPass(pass);
}
}
网友评论