1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- package com.echepei.utils.mail;
- import com.echepei.dto.mail.MailDto;
- import com.echepei.enums.MailTypeEnum;
- import jakarta.mail.Authenticator;
- import jakarta.mail.PasswordAuthentication;
- import jakarta.mail.Session;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Properties;
- /**
- * @author Rain
- */
- public class MailUtil {
- private static final Map<String, Session> SESSION_MAP = new HashMap<>(20);
- public static Session getSession(MailDto mailDto) {
- // 如果存在则直接返回
- if (SESSION_MAP.containsKey(mailDto.getMailFrom())) {
- return SESSION_MAP.get(mailDto.getMailFrom());
- }
- MailTypeEnum mailTypeEnum = MailTypeEnum.getMailTypeEnum(mailDto.getMailType());
- if (mailTypeEnum == null) {
- throw new RuntimeException("邮箱类型错误");
- }
- Properties properties = new Properties();
- properties.put("mail.smtp.host", mailTypeEnum.mailSmtpHost);
- properties.put("mail.smtp.port", mailTypeEnum.mailSmtpPort);
- properties.put("mail.smtp.auth", "true");
- properties.put("mail.smtp.starttls.enable", "true");
- Session session = Session.getInstance(properties, new Authenticator() {
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(mailDto.getMailUserName(), mailDto.getMailPassword());
- }
- });
- SESSION_MAP.put(mailDto.getMailFrom(), session);
- return session;
- }
- }
|