一、yml
mail:
host: smtp.qq.com
username: 发件人邮箱
password: SMTP授权密码
port: 25
protocol: smtp
default-encoding: UTF-8
二、pom
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
三、service
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @Service public class MailService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Value("${spring.mail.username}") private String from; @Autowired private JavaMailSender mailSender; /** * 简单文本邮件 * @param to 接收者邮件 * @param subject 邮件主题 * @param contnet 邮件内容 */ public void sendSimpleMail(String to, String subject, String contnet){ SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(contnet); message.setFrom(from); mailSender.send(message); } }
四、controller层调用,将参数传进去