##1 首先业务分析
基于面向对象大法:发送邮件须有四件事要做:创建邮件对象,创建通知事件,监听事件,推送业务。
1,邮件对象; 首先创建一个邮件发送对象:
/**
* @author czbcxy
* @date 2020-04-13 10:42:02
* 说明:一个非常简单的邮件实体类
*/
@Data
@Accessors(chain = true)
public class SendEmailDTO implements Serializable {
private static final long serialVersionUID = 1854143598655825198L;
//邮件发送人
private String from = "k995211314@163.com";
//邮件接收人
private String[] to = new String[]{"k995211314@163.com"};
//邮件主题
private String subject;
//邮件内容
private String text;
private String replyTo;
private String cc;
private String bcc;
private String sentDate;
}
2,通知事件;基于spirng创建一个通知事件:有很多种方法,这里使用给一个最普遍的:
/**
* @author czbcxy
* @date 2020-04-13 10:42:46
* 说明:通知事件
*/
@Data
public class SendEmailEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
public SendEmailEvent(Object source) {
super(source);
}
}
3,监听事件;基于spirng创建一个监听事件:
/**
* @author 程征波
* @date 2020-03-13 21:38:28
* 说明:事件监听器到通知,进行执行者
* 实现ApplicationListener接口,同时声明监听的事件类型
*/
@Component
public class SendEmailListener implements ApplicationListener<SendEmailEvent> {
@Autowired
private JavaMailSenderImpl javaMailSenderImpl;
@Override
public void onApplicationEvent(SendEmailEvent event) {
sendEmail(event);
}
private void sendEmail(SendEmailEvent event) {
SendEmailDTO source = (SendEmailDTO)event.getSource();
SimpleMailMessage message = new SimpleMailMessage();
BeanUtils.copyProperties(source, message);
System.out.println(message.toString());
javaMailSenderImpl.send(message);
System.out.println("====== 消息发送成功 ======");
}
}
4,推送事件; 基于sping创建一个推送事件;可用于在任何业务类中
@Component
public class ServerPublisher {
@Autowired
private ApplicationEventPublisher publisher;
public void sendEmail(SendEmailDTO dto) {
publisher.publishEvent(new SendEmailEvent(dto));
}
}
进行测试:
@SpringBootTest
@RunWith(SpringRunner.class)
public class SendEmailTest {
@Autowired
ServerPublisher serverPublisher;
@Test
public void test() {
SendEmailDTO sendEmailDTO = new SendEmailDTO();
sendEmailDTO.setSubject("Hello");
sendEmailDTO.setText("Hello World!");
serverPublisher.sendEmail(sendEmailDTO);
}
}
测试结果: