服务器 amazon
服务器需要配置出站规则,在安全组将 465 端口号 设置为可出站
账号 gmail 账号 密码即可
public class EmailServiceImpl implements EmailService {
@Value("${javamail.host}")
private String host; //smtp.gmail.com
@Value("${javamail.port}")
private Integer port;//465
@Value("${javamail.username}")
private String userName;//账号
@Value("${javamail.password}")
private String password;//密码
//发送邮件的模板引擎
@Autowired
private FreeMarkerConfigurer configurer;
public MessageTo<Object> sendModelMail(EmailInfoMo info, String code) {
try {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
mailSender.setPort(port);
mailSender.setUsername(userName);
mailSender.setPassword(password);
Properties mailProp = mailSender.getJavaMailProperties();
mailProp.put("mail.transport.protocol", "smtp");
mailProp.put("mail.smtp.auth", "true");
mailProp.put("mail.smtp.starttls.enable", "true");
mailProp.put("mail.smtp.starttls.required", "true");
mailProp.put("mail.smtp.ssl.enable", "true");
Template template = configurer.getConfiguration().getTemplate(info.getTempleteName());
Map model = new HashMap<>();
model.put("code", code);
String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
helper.setFrom(userName);
helper.setTo(info.getTo());
helper.setSubject(info.getSubject());
helper.setText(text, true);
mailSender.send(message);
return new MessageTo<>(1, MessageToCode.AUTHCODE_SEND_SUCCESS);
} catch (Exception e) {
e.printStackTrace();
}
return new MessageTo<>(0, MessageToCode.AUTHCODE_SEND_FAIL);
}
}
若出现连接超时,原因为防火墙,或放在外网服务器进行测试