正安网站建设外链网站推荐几个
步骤
- 一、添加邮件相关依赖
- 二、配置邮件服务器
- 三、发送邮件
- PS:SMTP 发送失败的解决方案
一、添加邮件相关依赖
在 pom.xml 文件中添加 JavaMail 和 Spring Mail 相关的依赖。示例代码如下:
<dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.6.2</version>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId>
</dependency>
二、配置邮件服务器
在 application.properties 文件中配置邮件服务器相关参数。示例代码如下:
# SMTP服务器地址,QQ邮箱的SMTP服务器地址为smtp.qq.com
spring.mail.host=smtp.qq.com
# SMTP服务器端口,QQ邮箱的SMTP服务器端口为465或587
spring.mail.port=465
# 使用SSL协议连接SMTP服务器
spring.mail.protocol=smtps
# 邮箱用户名,一般以自己的QQ邮箱为发送方,所以写自己的QQ邮箱即可
spring.mail.username=yourusername@qq.com
# 邮箱授权码,不是密码
spring.mail.password=yourauthorizationcode
# 邮件编码
spring.mail.default-encoding=UTF-8
# 是否开启调试模式
spring.mail.debug=true
注意: 服务器发送QQ邮件,需要QQ邮箱的授权码而不是QQ密码进行身份验证。可以通过在 QQ 邮箱的设置中开启POP3/SMTP服务,并记下授权码,步骤如下:
- 登录QQ邮箱,进入邮箱首页。
- 点击页面左上角的“设置”按钮,选择“账户”。
- 在“账户”设置的页面中,找到“POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务”选项卡。
- 在“POP3/SMTP服务”部分,点击“开启”按钮。
- 记住授权码
三、发送邮件
@Service
public class UserInfoServiceImpl implements UserInfoService {@Resourceprivate UserInfoMapper userInfoMapper;@Resourceprivate JavaMailSender javaMailSender;// 邮件服务器// 发送邮箱验证码@Overridepublic int sendEmailVerCode(UserInfoDto userInfoDto) {// 创建邮件消息SimpleMailMessage message = new SimpleMailMessage();message.setFrom("yourusername@qq.com");//必须写与配置相同的QQ邮箱message.setTo(userInfoDto.getEmail());//设置接收用户的邮箱message.setSubject("Reset Password Verification Code");// 生成 6 位数字验证码Random random = new Random();int verificationCode = random.nextInt(899999) + 100000;message.setText("Your verification code is: " + verificationCode);// 发送邮件javaMailSender.send(message);// 将验证码返回前端(通过前端直接验证即可)return verificationCode;}
}
PS:SMTP 发送失败的解决方案
建议采用以下方法之一进行排除:
- 如果您的网络使用的是动态 IP 地址,请尝试更换当前 IP 地址再次发送邮件。可以通过重启路由器或重新拨号来更换动态 IP。
- 如果您正在使用 VPN 或代理服务,请尝试暂停使用并再次发送邮件。
- 检查您的防火墙设置,确保您的 Spring Boot 应用程序可以通过防火墙发送邮件。
- 检查您的 QQ 邮箱账户是否存在异常,例如异常登录、账单欠费等情况,这可能会导致邮件无法发送成功。