邮件发送,在我们的日常开发中,也非常的多,Springboot也帮我们做了支持
-
邮件发送需要引入spring-boot-start-mail
-
SpringBoot 自动配置MailSenderAutoConfiguration
-
定义MailProperties内容,配置在application.yml中
-
自动装配JavaMailSender
-
测试邮件发送
1、引入pom依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
2、查看自动配置类:MailSenderAutoConfiguration
@Configuration( proxyBeanMethods = false ) @ConditionalOnClass({MimeMessage.class, MimeType.class, MailSender.class}) @ConditionalOnMissingBean({MailSender.class}) @Conditional({MailSenderAutoConfiguration.MailSenderCondition.class}) @EnableConfigurationProperties({MailProperties.class}) @Import({MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class}) public class MailSenderAutoConfiguration { public MailSenderAutoConfiguration() { } static class MailSenderCondition extends AnyNestedCondition { MailSenderCondition() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @ConditionalOnProperty( prefix = "spring.mail", name = {"jndi-name"} ) static class JndiNameProperty { JndiNameProperty() { } } @ConditionalOnProperty( prefix = "spring.mail", name = {"host"} ) static class HostProperty { HostProperty() { } } } }
然后我们去看下配置文件MailProperties
public class MailProperties { private static final Charset DEFAULT_CHARSET; private String host; private Integer port; private String username; private String password; private String protocol = "smtp"; private Charset defaultEncoding; private Map<String, String> properties; private String jndiName; ..... }
MailProperties 中就是我们能自己去定义的属性。
3、配置文件:
spring.mail.username=1763204261@qq.com spring.mail.password=qq邮箱授权码 spring.mail.host=smtp.qq.com # qq需要配置ssl spring.mail.properties.mail.smtp.ssl.enable=true
获取授权码:在QQ邮箱中的设置->账户->开启pop3和smtp服务
4、Spring单元测试
@Autowired JavaMailSenderImpl mailSender; @Test public void emailTest(){ //邮件设置1:一个简单的邮件 SimpleMailMessage message = new SimpleMailMessage(); message.setSubject("通知-你收到邮件了"); message.setText("神圣的时刻来了!"); message.setTo("1763204261@qq.com"); message.setFrom("1763204261@qq.com"); mailSender.send(message); }
查看邮箱,邮件接收成功!
上面这个是比较简单的邮件发送,有时候会需要更复杂的,比如带入文件之类的:
此时需要用 MimeMessage
@Autowired JavaMailSenderImpl mailSender; @Test public void contextLoads2() throws MessagingException { //邮件设置2:一个复杂的邮件 MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setSubject("通知-收到文件邮件"); helper.setText("<b style='color:red'>又是神圣的时刻!</b>",true); //发送附件 helper.addAttachment("1.jpg",new File("G:\\1.jpg")); helper.setTo("1763204261@qq.com"); helper.setFrom("1763204261@qq.com"); mailSender.send(mimeMessage); }
测试
和预想的一样!