package com.yssh.service; import com.yssh.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; /** * 邮件服务类 * * @author www * @date 2024-03-21 */ @Service public class EmailService { @Value("${email.userName}") private String userName; @Value("${email.password}") private String password; @Value("${email.smtpHost}") private String smtpHost; @Value("${email.smtpPort}") private String smtpPort; @Value("${email.smtpAuth}") private String smtpAuth; @Value("${email.smtpTls}") private String smtpTls; @Value("${email.from}") private String from; @Value("${email.to}") private String to; @Value("${email.cc}") private String cc; protected final Logger logger = LoggerFactory.getLogger(this.getClass()); public Session createSession() { // 创建一个配置文件,并保存 Properties props = new Properties(); // SMTP服务器连接信息:126—smtp.126.com,163—smtp.163.com,qq-smtp.qq.com" props.put("mail.smtp.host", smtpHost); // SMTP主机名 props.put("mail.smtp.port", smtpPort); // 主机端口号:126—25,163—645,qq-587 props.put("mail.smtp.auth", smtpAuth); // 是否需要用户认证 props.put("mail.smtp.starttls.enale", smtpTls); // 启用TlS加密 Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }); // 控制台打印调试信息 session.setDebug(true); return session; } public Boolean send(String title, String text) { try { // 创建Session会话 Session session = createSession(); // 创建邮件对象 MimeMessage message = new MimeMessage(session); message.setSubject(title); message.setText(text); message.setFrom(new InternetAddress(from)); message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to)); //message.setRecipients(Message.RecipientType.CC, new InternetAddress[] {new InternetAddress("抄送人邮箱")}); if (!StringUtils.isEmpty(cc)) { String[] strs = cc.split(","); InternetAddress[] ias = new InternetAddress[strs.length]; for (int i = 0, c = strs.length; i < c; i++) { ias[i] = new InternetAddress(strs[i]); } message.setRecipients(Message.RecipientType.CC, ias); } // 发送 Transport.send(message); return true; } catch (Exception ex) { logger.error(ex.getMessage(), ex); return false; } } }