粘贴复制成风的国度,很少会有真正想解决问题的人
本篇博客借鉴的原文,其中有更详尽的介绍
发送前须知
登录密码
✔️ 登录密码不是邮箱密码,是授权码
不同邮箱授权码生成方式可能不同:
QQ 邮箱:设置 → 账户 → POP3/IMAP… 点生成授权码,按提示操作
GMail:按照这个提示操作
发送邮件服务器
✔️ 发送邮件服务器一般为 smtp.xxx.com
举例:
QQ 邮箱:smtp.qq.com
GMail:smtp.gmail.com
端口号一般为 587
或 465
。如果不使用 SSL,端口号一般是 25
不同邮箱对端口支持情况不同,具体信息可通过各个邮箱的设置页面查看(也可以挨个试)
发送邮件
依赖
Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
Gradle
implementation('org.springframework.boot:spring-boot-starter-mail')
JavaMailSender
配置 JavaMailSender
,之后用来发送邮件
@Bean
public JavaMailSender getJavaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
mailSender.setUsername("my.gmail@gmail.com");
mailSender.setPassword("password");
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
return mailSender;
}
发送简单的邮件。需要设置邮件中三个元素:To
Subject
Text
@Component
public class EmailServiceImpl implements EmailService {
@Autowired
public JavaMailSender emailSender;
public void sendSimpleMessage(
String to, String subject, String text) {
...
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
...
}
}
发送带附件的邮件
@Override
public void sendMessageWithAttachment(
String to, String subject, String text, String pathToAttachment) {
// ...
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
FileSystemResource file
= new FileSystemResource(new File(pathToAttachment));
helper.addAttachment("Invoice", file);
// Not use SSL -->
// <--
emailSender.send(message);
// ...
}
使用 SSL
// For using SSL -->
MailSSLSocketFactory socketFactory = null;
try {
socketFactory = new MailSSLSocketFactory();
socketFactory.setTrustAllHosts(true);
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
}
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", socketFactory);
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailUsername, mailPassword);
}
};
Session session = Session.getDefaultInstance(props, authenticator);
session.setDebug(true);
mailSender.setSession(session);
// <--