SpringBoot - 邮件任务入门

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/J080624/article/details/80960216

【1】引入starter-mail与邮件自动配置

pom文件依赖如下:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

该starter引入如下依赖:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
		</dependency>
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
		</dependency>

SpringBoot中对邮件任务做了自动配置,自动配置类MailSenderAutoConfiguration。

源码如下:

**
 * {@link EnableAutoConfiguration Auto configuration} for email support.
 *
 * @author Oliver Gierke
 * @author Stephane Nicoll
 * @author Eddú Meléndez
 * @since 1.2.0
 */
@Configuration
@ConditionalOnClass({ MimeMessage.class, MimeType.class })
@ConditionalOnMissingBean(MailSender.class)
@Conditional(MailSenderCondition.class)
@EnableConfigurationProperties(MailProperties.class)
@Import(JndiSessionConfiguration.class)
public class MailSenderAutoConfiguration {

	private final MailProperties properties;

	private final Session session;

	public MailSenderAutoConfiguration(MailProperties properties,
			ObjectProvider<Session> session) {
		this.properties = properties;
		this.session = session.getIfAvailable();
	}
// 用来发送邮件的实现类
	@Bean
	public JavaMailSenderImpl mailSender() {
		JavaMailSenderImpl sender = new JavaMailSenderImpl();
		if (this.session != null) {
			sender.setSession(this.session);
		}
		else {
			applyProperties(sender);
		}
		return sender;
	}

	private void applyProperties(JavaMailSenderImpl sender) {
		sender.setHost(this.properties.getHost());
		if (this.properties.getPort() != null) {
			sender.setPort(this.properties.getPort());
		}
		sender.setUsername(this.properties.getUsername());
		sender.setPassword(this.properties.getPassword());
		sender.setProtocol(this.properties.getProtocol());
		if (this.properties.getDefaultEncoding() != null) {
			sender.setDefaultEncoding(this.properties.getDefaultEncoding().name());
		}
		if (!this.properties.getProperties().isEmpty()) {
			sender.setJavaMailProperties(asProperties(this.properties.getProperties()));
		}
	}

	private Properties asProperties(Map<String, String> source) {
		Properties properties = new Properties();
		properties.putAll(source);
		return properties;
	}

	/**
	 * Condition to trigger the creation of a {@link JavaMailSenderImpl}. This kicks in if
	 * either the host or jndi name property is set.
	 */
	static class MailSenderCondition extends AnyNestedCondition {

		MailSenderCondition() {
			super(ConfigurationPhase.PARSE_CONFIGURATION);
		}

		@ConditionalOnProperty(prefix = "spring.mail", name = "host")
		static class HostProperty {

		}

		@ConditionalOnProperty(prefix = "spring.mail", name = "jndi-name")
		static class JndiNameProperty {

		}

	}

}


邮件属性配置类MailProperties源码示例如下:

/**
 * Configuration properties for email support.
 *
 * @author Oliver Gierke
 * @author Stephane Nicoll
 * @author Eddú Meléndez
 * @since 1.2.0
 */
@ConfigurationProperties(prefix = "spring.mail")
public class MailProperties {

	private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

	/**
	 * SMTP server host.
	 */
	private String host;

	/**
	 * SMTP server port.
	 */
	private Integer port;

	/**
	 * Login user of the SMTP server.
	 */
	private String username;

	/**
	 * Login password of the SMTP server.
	 */
	private String password;

	/**
	 * Protocol used by the SMTP server.
	 */
	private String protocol = "smtp";

	/**
	 * Default MimeMessage encoding.
	 */
	private Charset defaultEncoding = DEFAULT_CHARSET;

	/**
	 * Additional JavaMail session properties.
	 */
	private Map<String, String> properties = new HashMap<String, String>();

	/**
	 * Session JNDI name. When set, takes precedence to others mail settings.
	 */
	private String jndiName;

	/**
	 * Test that the mail server is available on startup.
	 */
	private boolean testConnection;
	//...
}

【2】简单消息发送示例

这里使用163邮箱服务器向QQ邮箱发送邮件。

application.properties对邮件属性配置实例如下:

spring.mail.username=jgc15993729750@163.com
# 这里使用授权码
spring.mail.password=xxxxx
spring.mail.host=smtp.163.com
spring.mail.protocol=smtp

spring.mail.properties.mail.smtp.ssl.enable=true

这里写图片描述


测试代码如下:

    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    public void testSimpleMessage(){
        
        SimpleMailMessage message = new SimpleMailMessage();

        message.setSubject("第一封测试邮件");
        message.setText("邮件测试。。。");

        message.setFrom("jgc15993729750@163.com");
        message.setTo("1274654983@qq.com");

        mailSender.send(message);
    }

手动创建JavaMailSenderImpl并设置属性:

	 @Test
    public void testSimpleMessage(){
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

        mailSender.setUsername("jgc15993729750@163.com");
		//网易邮箱授权码
        mailSender.setPassword("xxxxxxx");
        mailSender.setHost("smtp.163.com");
        mailSender.setProtocol("smtp");
        //mail.smtp.ssl.enable=true
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.ssl.enable","true");
        mailSender.setJavaMailProperties(properties);
        System.out.println(mailSender);

        SimpleMailMessage message = new SimpleMailMessage();

        message.setSubject("第一封测试邮件");
        message.setText("邮件测试。。。");

        message.setFrom("jgc15993729750@163.com");
        message.setTo("1274654983@qq.com");

        mailSender.send(message);
    }

【3】复杂消息发送示例

测试代码如下:

	@Test
    public void testMimeMessage() throws  Exception{
        // 创建复杂消息
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);

        helper.setSubject("第二封邮件");
        helper.setText("<b style='color:red'>邮件测试....</b>",true);

        helper.setFrom("jgc15993729750@163.com");
        helper.setTo("1274654983@qq.com");

        helper.addAttachment("1.jpg",new File("C:\\Users\\12746\\Pictures\\22\\1.jpg"));
        helper.addAttachment("2.jpg",new File("C:\\Users\\12746\\Pictures\\22\\2.jpg"));

        mailSender.send(mimeMessage);
    }

测试结果如下图:

这里写图片描述

更多详情参考博文:
如何使用 Spring Boot 开发邮件系统

展开阅读全文

没有更多推荐了,返回首页