2.01 发送邮件

使用spring boot发送邮件

在用户注册时,给用户发送邮件,让用户碘酒邮件中的链接完成账号激活!

发送邮件的客户端代码

package com.nowcoder.community.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class MailClient {

	private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

	@Autowired
	private JavaMailSender mailSender;

	@Value("${spring.mail.username}")
	private String from;

	/***
	 * 
	 * @param to 发送邮件给谁?
	 * @param subject
	 * @param content
	 */
	public void sendMail(String to, String subject, String content) {
		try {
			MimeMessage message = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(message);
			helper.setFrom(from);
			helper.setTo(to);
			helper.setSubject(subject);
			helper.setText(content, true);
			mailSender.send(helper.getMimeMessage());
		} catch (MessagingException e) {
			logger.error("发送邮件失败:" + e.getMessage());
		}
	}

}

  

springboot发邮件的相关配置

application.properties

# MailProperties
spring.mail.host=smtp.sina.cn
spring.mail.port=465
spring.mail.username=lpzhxxx@sina.cn
#0fcd058d89ee14a8(客户端授权码)
# 注意:新浪邮箱开启客户端授权码后,只能使用授权码登录,不能再使用密码认证
spring.mail.password=0fcd058d89ee14a8
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true

  

单元测试类

package com.nowcoder.community;

import com.nowcoder.community.util.MailClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests {

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void testTextMail() {
        mailClient.sendMail("lpzh1218@126.com", "TEST", "Welcome.");
    }

    @Test
    public void testHtmlMail() {
        Context context = new Context();
        context.setVariable("username", "sunday");

        String content = templateEngine.process("/mail/demo", context);
        System.out.println(content);

        mailClient.sendMail("lpzh1218@126.com", "HTML", content);
    }

}

 

测试效果

  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )\___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.5.RELEASE)

2020-03-22 15:55:32,814 INFO [main] c.n.c.MailTests [StartupInfoLogger.java:50] Starting MailTests on lzph-pc with PID 8360 (started by admin in E:
owcoder
owcoder-workspacecommunity-2.1)
2020-03-22 15:55:32,817 DEBUG [main] c.n.c.MailTests [StartupInfoLogger.java:53] Running with Spring Boot v2.1.5.RELEASE, Spring v5.1.7.RELEASE
2020-03-22 15:55:32,819 INFO [main] c.n.c.MailTests [SpringApplication.java:675] No active profile set, falling back to default profiles: default
2020-03-22 15:55:40,542 INFO [main] o.s.s.c.ThreadPoolTaskExecutor [ExecutorConfigurationSupport.java:171] Initializing ExecutorService 'applicationTaskExecutor'
2020-03-22 15:55:41,497 INFO [main] o.s.b.a.w.s.WelcomePageHandlerMapping [WelcomePageHandlerMapping.java:61] Adding welcome page template: index
2020-03-22 15:55:42,665 INFO [main] c.n.c.MailTests [StartupInfoLogger.java:59] Started MailTests in 11.173 seconds (JVM running for 13.768)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>邮件示例</title>
</head>
<body>
    <p>欢迎你, <span style="color:red;">sunday</span>!</p>
</body>
</html>
2020-03-22 15:55:50,367 INFO [Thread-3] o.s.s.c.ThreadPoolTaskExecutor [ExecutorConfigurationSupport.java:208] Shutting down ExecutorService 'applicationTaskExecutor'

  

 

原文地址:https://www.cnblogs.com/lpzh/p/12546590.html