-
之前的发邮件的话比较繁琐,spring bbot帮我们简化了开发,引入mail的启动类支持
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
-
既然spring boot中已经配置了,说明它里面肯定有一个关于mail的自动配置类: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 final Map<String, String> properties; private String jndiName;
-
配置自己与mail相关的配置
[email protected] spring.mail.password=qq邮箱授权码 spring.mail.host=smtp.qq.com # qq需要配置ssl spring.mail.properties.mail.smtp.ssl.enable=true
-
进行代码测试
@Autowired JavaMailSenderImpl mailSender; @Test public void emailTest(){ //邮件设置1:一个简单的邮件 SimpleMailMessage message = new SimpleMailMessage(); message.setSubject("邮件主题"); message.setText("邮件正文"); message.setTo("[email protected]"); message.setFrom("[email protected]"); mailSender.send(message); }
-
若带有附件的复杂的邮件发送
@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("F:/1.jpg"));
helper.setTo("[email protected]");
helper.setFrom("[email protected]");
mailSender.send(mimeMessage);
}
```
标签:qq,spring,boot,private,mail,class,邮件
From: https://www.cnblogs.com/hytip/p/18203242