一只倔强的笨猪

【Spring Boot】邮件发送

1.导入Maven包。

		<!-- 邮件发送 -->
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-mail</artifactId>
		</dependency>

2.配置属性文件。

#这个配置可以为空,后面我们可以自定义从数据库
#或者从文件拿到对应的参数实现动态的配置邮件
#邮件发送配置
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.编写邮件实体类。

package com.liuliu.com.domain;

import lombok.Data;

//我这里用了lombok插件,所有不用写get/set方法
@Data
public class Email {
	private Integer emailId;
	private String emailHost;
	private Integer emailPort;
	private String emailUsername;
	private String emailPassword;
	private String emailCall;
	private Integer emailPower;
}

4.设置邮件发送的接口类。

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);
}

5.实现邮件发送的方法。

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);
	}
}
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注