1. 登录Gmail
Gmail网址
点击右上角“小齿轮”,然后点击"查看所有设置"
点击“转发和 POP/IMAP”,按图中设置,然后点击保存:
2. 启用两步验证(https://myaccount.google.com/security)
登录上述网址,找到“安全”(Security)
点击“两步验证”
开启“两步验证”,小编这里已经开启了,所以显示的关闭.
3. 创建应用程序密码
搜索"App passwords",点击第一个
输入程序名称,点击“创建”后会显示一个密码,该密码可以用来发送邮件.
4. Java程序实现(方式1)
4.1 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
4.2 yml配置
spring
mail:
host: smtp.gmail.com
port: 587
username: xxx@gmail.com
password: xxx # 第三步的应用程序密码
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
4.3 代码
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
/**
* 邮件发送服务实现类
*/
@Slf4j
@RequiredArgsConstructor
@Service
public class MailSendService {
@Value("${spring.mail.username}")
private String mailFrom;
private final JavaMailSender javaMailSender;
@Override
public void sendMailSimple(String to, String subject, String text) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
// 发件人
simpleMailMessage.setFrom(mailFrom);
// 收件人
simpleMailMessage.setTo(to);
// 邮件主题
simpleMailMessage.setSubject(subject);
// 邮件内容
simpleMailMessage.setText(text);
javaMailSender.send(simpleMailMessage);
}
@Override
public void sendWithAttach(String to, String subject, String text, MailAttachInfoDTO ...attachInfos) {
MimeMessage message = javaMailSender.createMimeMessage();
try{
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(mailFrom);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
for(MailAttachInfoDTO attachInfo : attachInfos) {
if(attachInfo == null) continue;
helper.addAttachment(attachInfo.getAttachName(), attachInfo.getAttachSource());
}
}catch (MessagingException e) {
log.warn("MailSendServiceImpl.sendWithAttach failed.", e);
}
javaMailSender.send(message);
}
}
4.4 设置代理
在调试的时候需要梯子,否则可能访问不了Gmail的服务器:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@EnableJpaAuditing
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
// 设置代理地址、端口 你们调试的时候替换成自己的代理地址端口
System.setProperty("http.proxyHost", "192.168.0.12");
System.setProperty("http.proxyPort", "10183");
SpringApplication.run(TestApplication.class, args);
}
}
5. Java程序实现(方式2-动态发送者)
由于我们项目中,原本已经存在发送邮件的功能,yml已经配置了其他的邮箱,而此时又来一个新需求,需要使用不同的邮箱来发送。所以这里我使用了动态设置发送人的方式。
DynamicMailSender.java
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import java.util.Properties;
public class DynamicMailSender {
public static JavaMailSender createGmailSender(String username, String password) {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
mailSender.setUsername(username);
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.smtp.connectiontimeout", "5000");
// props.put("mail.smtp.timeout", "5000");
// props.put("mail.smtp.writetimeout", "5000");
props.put("mail.debug", "true");
return mailSender;
}
}
EmailService.java
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class EmailService {
/**
* 发送Gmail邮件
* @param from 发送者邮箱
* @param password 应用程序密码
* @param to 接收者邮箱
* @param subject 邮件主题
* @param text 邮件内容
* @return 发送是否成功
*/
public boolean sendGmailSimple(String from, String password, String to, String subject, String text) {
try {
JavaMailSender mailSender = DynamicMailSender.createGmailSender(from, password);
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
return true;
} catch (Exception e) {
log.info("EmailService 发送gmail失败.", e);
}
return false;
}
/**
* 发送Gmail邮件
* @param fromEmail 发送者邮箱
* @param fromName 发送者昵称
* @param password 应用程序密码
* @param to 接收者邮箱
* @param subject 邮件主题
* @param text 邮件内容
* @return 发送是否成功
*/
public boolean sendGmailSimple(String fromEmail, String fromName, String password, String to, String subject, String text) {
if (StringUtils.isBlank(fromName)) {
return sendGmailSimple(fromEmail, password, to, subject, text);
}
return sendGmailSimple(fromEmail, fromName, password, to, subject, text, false);
}
/**
* 发送Gmail邮件
* @param fromEmail 发送者邮箱
* @param fromName 发送者昵称
* @param password 应用程序密码
* @param to 接收者邮箱
* @param subject 邮件主题
* @param text 邮件内容
* @param html 内容是否使用html格式
* @return 发送是否成功
*/
public boolean sendGmailSimple(String fromEmail, String fromName, String password, String to, String subject, String text, boolean html) {
try {
JavaMailSender mailSender = DynamicMailSender.createGmailSender(fromEmail, password);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(fromEmail, fromName);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, html);
mailSender.send(message);
return true;
} catch (Exception e) {
log.info("EmailService 发送gmail失败.", e);
}
return false;
}
}