springboot 发送邮箱

pom.xml

<dependency>
	<groupId>com.sun.mailgroupId>
	<artifactId>javax.mailartifactId>
	<version>1.6.2version>
dependency>

application.yml

spring:
  mail:
    host: smtp.163.com
    port: 25
    username: asd.163.com
    password: 开启imap/smtp服务时的授权码
    properties:
      mail:
        debug: true # 开启邮件的日志打印,方便我们进行错误的排查

controller/MailController.java

@RestController
public class MailController {

	private static final Logger logger = LoggerFactory.getLogger(MailController.class);
	
	@Resource
	private JavaMailSender javaMailSender;

	@Resource
	private MailProperties mailProperties;

	@GetMapping("/send")
	public String sendMail() {

		try {
			MimeMessage mimeMessage = javaMailSender.createMimeMessage();
			MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);// 加参数true就表示允许发送附件
			mimeMessageHelper.setSubject("mail test title");// 设置邮件标题
			mimeMessageHelper.setTo("[email protected]");// 向哪个邮箱发送,邮箱接收者
			// mimeMessageHelper.setText("mail test content");// 邮箱内容,纯文本
			mimeMessageHelper.setText("mail test content", true);// 邮箱内容,第二个参数是是否为html
			mimeMessageHelper.setSendDate(new Date());//发送日期
			mimeMessageHelper.setFrom(mailProperties.getUsername());// 这个邮件来自哪个邮箱,邮件发送者

			// 设置附件(参数1 文件名称 参数2 文件路径)
			mimeMessageHelper.addAttachment("asd.word",new File("d:\\asd.word"));
			// 附件是可以多个发送的,继续调用addAttachment就行
			// mimeMessageHelper.addAttachment("asd.xls",new File("d:\\asd.xls"));
			
			javaMailSender.send(mimeMessage);// 发送邮件
		}catch(Exception e) {
			logger.error("mail send error", e);
			return "error";
		}
		return "success";
	}	
}

因为邮箱发送有一定的延迟,而且发送是否成功对业务没有太大的影响,所以一般建议用异步发送。

你可能感兴趣的:(Java,Web,spring,boot,邮件发送)