maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.properties 的配置
#服务器 spring.mail.host=smtp.exmail.qq.com #发送者邮箱 spring.mail.username=xxx #授权码 spring.mail.password=xxx #编码格式 spring.mail.default-encoding=utf-8 # 设置是否需要认证,如果为true,那么用户名和密码就必须的, #如果设置false,可以不设置用户名和密码,当然也得看你的对接的平台是否支持无密码进行访问的。 spring.mail.properties.mail.smtp.auth=true # STARTTLS[1] 是对纯文本通信协议的扩展。它提供一种方式将纯文本连接升级为加密连接(TLS或SSL),而不是另外使用一个端口作加密通信。 spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.stattls.required=true
具体实现
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
@Service
public class MailService {
@Autowired
JavaMailSender mailSender;
public Object sendEmail(String from,String msg,String to,String subject){
try{
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from); // 发送者邮箱
message.setTo(to); // 接受者邮箱
message.setSubject(subject); // 主题
message.setText(msg); // 内容
mailSender.send(message);
return "成功";
}catch(Exception ex){
System.out.println(ex.getMessage());
return "失败";
}
}
}