1.导入Maven包
<!– 邮件发送 –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置属性文件
application.properties
#这个配置可以为空,后面我们可以自定义从数据库
#或者从文件拿到对应的参数实现动态的配置邮件
#邮件发送配置
spring.mail.host=
spring.mail.username=
spring.mail.password=
spring.mail.port= 465
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
spring.mail.properties.smtp.auth=true
spring.mail.properties.smtp.starttls.enable=true
spring.mail.properties.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enable=true
3.编写邮件代码
Email.java
package com.liuliu.com.service;
import com.liuliu.com.domain.Email;
public interface EmailService {
public void emailText(Email email, String to, String subject, String text);
}
EmailServiceImpl.java
package com.liuliu.com.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.liuliu.com.domain.Email;
import com.liuliu.com.service.EmailService;
@Service("EmailServiceImpl")
public class EmailServiceImpl implements EmailService{
@Autowired
private JavaMailSenderImpl mailSender;
public void emailText(Email email, String to, String subject, String text) {
// 发送邮件
//email发送属性的配置
//to收信人
//subject发送的标题
//text发送的内容
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
mailSender.setUsername(email.getEmailUsername());
mailSender.setHost(email.getEmailHost());
mailSender.setPassword(email.getEmailPassword());
mailSender.setPort(email.getEmailPort());
simpleMailMessage.setTo(to);
simpleMailMessage.setFrom(email.getEmailCall());
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(text);
mailSender.send(simpleMailMessage);
}
}
评论