SpringBoot----实现简单的邮件发送

SpringBoot----实现简单的邮件发送

1、新建一个Maven项目springboot8,使用jdk8,在配置文件pom.xml中添加如下依赖:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.etc</groupId>
	<artifactId>springboot8</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboot8</name>
	<url>http://maven.apache.org</url>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.7.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<!-- SpringBoot导入的jar包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- 邮件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>
		<!-- 模板thymeleaf -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<!-- SpringBoot 测试包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

2、在com.etc.springboot8包下新建一个Application.java启动类:

package com.etc.springboot8;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
 * @Description:启动类
 * @author zoey
 * @date:2018年3月16日
 */
@SpringBootApplication
@ComponentScan(basePackages="com.etc.*")
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
		System.out.println("启动完成");
	}
}

3、在src/main/resources文件夹下新建application.properties文件如下:

#############邮箱服务器地址(此处我使用的是163的邮箱)#############
spring.mail.host=smtp.163.com
#############用户名(此处我填写的是163网站登录的用户名)#############
[email protected]
#############授权码(此处我填写的是163网站用户的授权码)#############
spring.mail.password=xxxx
spring.mail.default-encoding=UTF-8
#############发送邮件的人#############
[email protected]

163网站授权码的获取方式:(因为发送的用户是163网站的用户,所以使用163网站的授权码)


4、在com.etc.service包下新建MailService.java接口如下:

package com.etc.service;

/**
 * @Description:Service接口,定义邮件发送的方法
 * @author zoey
 * @date:2018年3月16日
 */
public interface MailService {
	 void sendSimpleMail(String to, String subject, String content);
	 void sendHtmlMail(String to, String subject, String content);
	 void sendAttachmentsMail(String to, String subject,String content, String filePath);
}

5、在com.etc.service.impl包下新建MailServiceImpl.java类如下:

package com.etc.service.impl;

import java.io.File;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.etc.service.MailService;

/**
 * @Description:邮件发送的实现类
 * @author zoey
 * @date:2018年3月16日
 */
@Service
@Component
public class MailServiceImpl implements MailService{

	@Autowired
	private JavaMailSender mailSender;

	@Value("${mail.fromMail.addr}")
	private String from;
	
	/**
	 * @Description:发送简单邮件(收件人,主题,内容都暂时写死)
	 * @return
	 * @author:zoey
	 * @date:2018年3月16日
	 */
	@Override
	public void sendSimpleMail(String to, String subject, String content) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(to);
		message.setSubject(subject);
		message.setText(content);
		try {
			mailSender.send(message);
			System.out.println("简单邮件发送成功!");
		} catch (Exception e) {
			System.out.println("发送简单邮件时发生异常!"+e);
		}
	}
	
	/**
	 * @Description:发送Html邮件(收件人,主题,内容都暂时写死)
	 * @return
	 * @author:zoey
	 * @date:2018年3月16日
	 */
	@Override
	public void sendHtmlMail(String to, String subject, String content) {
	    MimeMessage message = mailSender.createMimeMessage();
	    try {
	        MimeMessageHelper helper = new MimeMessageHelper(message, true);   //true表示需要创建一个multipart message
	        helper.setFrom(from);
	        helper.setTo(to);
	        helper.setSubject(subject);
	        helper.setText(content, true);
	        mailSender.send(message);
	        System.out.println("html邮件发送成功");
	    } catch (MessagingException e) {
	    	System.out.println("发送html邮件时发生异常!"+e);
	    }
	}
	
	/**
     * 发送带附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath){
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            //helper.addAttachment("test"+fileName, file);

            mailSender.send(message);
            System.out.println("带附件的邮件已经发送。");
        } catch (MessagingException e) {
        	System.out.println("发送带附件的邮件时发生异常!"+e);
        }
    }
}

6、在com.etc.controller包下新建ServiceController.java类如下:

package com.etc.controller;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.etc.service.MailService;

/**
 * @Description:发送邮件的Controller
 * @author zoey
 * @date:2018年3月16日
 */
@RestController
@RequestMapping("/mail")
public class MailController {
	@Autowired
	private MailService mailService;
	
	@Autowired
	private TemplateEngine templateEngine;
	
	/**
	 * @Description:发送简单邮件(收件人,主题,内容都暂时写死)
	 * 访问地址:http://localhost:8080/mail/sendSimpleMail
	 * @return
	 * @author:zoey
	 * @date:2018年3月16日
	 */
	@RequestMapping("/sendSimpleMail")
	public String sendSimpleMail() {
		String to = "[email protected]";
		String subject = "test simple mail";
		String content = "hello, this is simple mail";
		mailService.sendSimpleMail(to, subject, content);
		return "success";
	}
	/**
	 * @Description:发送Html格式的邮件(收件人,主题,内容都暂时写死)
	 * 访问地址:http://localhost:8080/mail/sendHtmlMail
	 * @return
	 * @author:zoey
	 * @date:2018年3月16日
	 */
	@RequestMapping("/sendHtmlMail")
	public String  sendHtmlMail() {
		String to = "[email protected]";
		String subject = "test html mail";
		String content = "hello, this is html mail";
		mailService.sendHtmlMail(to, subject, content);
		return "success";
	}
	


	/**
	 * @Description:发送带有附件的邮件
	 * 访问地址:http://localhost:8080/mail/sendAttachmentsMail
	 * @author:zoey
	 * @date:2018年3月16日
	 */
	@Test
	@RequestMapping("/sendAttachmentsMail")
	public String sendAttachmentsMail() {
		String filePath="D:\\课外书籍\\jQuery权威指南.pdf";
		mailService.sendAttachmentsMail("[email protected]", "主题:带附件的邮件", "有附件,请查收!", filePath);
		return "success";
	}
	
	
	/**
	 * @Description:发送模板邮件
	 * 访问地址:http://localhost:8080/mail/sendTemplateMail
	 * @author:zoey
	 * @date:2018年3月16日
	 */
	@Test
	@RequestMapping("/sendTemplateMail")
	public String sendTemplateMail() {
		//创建邮件正文
		Context context = new Context();
		context.setVariable("user", "zoey");
		context.setVariable("web", "夏梦雪");
		context.setVariable("company", "测试公司");
		context.setVariable("product","梦想产品");
		String emailContent = templateEngine.process("emailTemplate", context);
		mailService.sendHtmlMail("[email protected]","主题:这是模板邮件",emailContent);
		return "sucess";
	}
}

7、在src/main/resources文件夹下新建templates文件夹,在文件夹下新建emailTemplate.html文件如下:

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>Title</title>
    </head>
    <body>
    	<p th:text="'尊敬的 ' + ${user} + '用户:'"></p>
                  
        <p th:text=" '恭喜您注册成为'+${web}+'网的用户,同时感谢您对'+${company}+'的关注与支持并欢迎您使用'+${product}+'的产品与服务。'"></p>
    	
    </body>
</html>

8、在src/test/java文件夹下,com.etc.springboot8包下新建ApplicationTest.java类如下:

package com.etc.springboot8;

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.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.etc.service.MailService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {
	@Autowired
	private MailService mailService;

	@Autowired
	private TemplateEngine templateEngine;

	@Test
	public void testSimpleMail() throws Exception {
		mailService.sendSimpleMail("[email protected]","test simple mail"," hello this is simple mail");
	}
	/**
	 * 发送简单邮件时发生异常!
	 * org.springframework.mail.MailAuthenticationException: Authentication failed; 
	 * nested exception is javax.mail.AuthenticationFailedException: 535 Error: authentication failed
	 * 
	 * application.properties文件中的password是授权码,而不是真的登录密码
	 * 
	 *  com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.163.com , 25; timeout -1;
	 *  连不上
	 *  spring.mail.host=smtp.163.com 后面多了一个空格
	 */

	/**
	 * @Description:发送模板邮件
	 * @author:zoey
	 * @date:2018年3月16日
	 */
	@Test
	public void sendTemplateMail() {
		//创建邮件正文
		Context context = new Context();
		context.setVariable("user", "zoey");
		context.setVariable("web", "夏梦雪");
		context.setVariable("company", "测试公司");
		context.setVariable("product","梦想产品");
		String emailContent = templateEngine.process("emailTemplate", context);
		mailService.sendHtmlMail("[email protected]","主题:这是模板邮件",emailContent);
	}

	/**
	 * @Description:发送带有附件的邮件
	 * 
	 * @author:zoey
	 * @date:2018年3月16日
	 */
	@Test
	public void sendAttachmentsMail() {
		String filePath="D:\\课外书籍\\jQuery权威指南.pdf";
		mailService.sendAttachmentsMail("[email protected]", "主题:带附件的邮件", "有附件,请查收!", filePath);
	}

}

9、运行:Application.java-->Run As,然后在页面访问:

(1)发送简单邮件:http://localhost:8080/mail/sendSimpleMail


(2)发送Html格式的邮件:http://localhost:8080/mail/sendHtmlMail


(3)发送带有附件的邮件:http://localhost:8080/mail/sendAttachmentsMail


(4)发送模板邮件:http://localhost:8080/mail/sendTemplateMail


10、运行:也可以直接在测试类ApplicationTest.java类中运行:Run As-->JUnit Test,结果与上面一致。


总结:

1、SpringBoot实现邮件发送的要点:

  • 需要引入邮件的依赖包(spring-boot-starter-mail)
  • 需要在配置文件中配置邮件相关的信息(服务器地址、用户名、授权码、发送人等)
  • 需要指定收件人、发件人、主题、内容、然后调用发送邮件的方法
  • 邮件发送使用模板时,可以使用thymeleaf或者freemarker模板实现,需要在pom.xml中引入依赖包,在模板中定义动态的内容,然后在java代码中定义动态代码的值

2、邮件发送失败:

(1)报错如下:

org.springframework.mail.MailAuthenticationException: Authentication failed; 
nested exception is javax.mail.AuthenticationFailedException: 535 Error: authentication failed

原因:配置文件application.properties中的password字段错误,不是真的密码,而是授权码

解决方法:password字段填写授权码

(2)报错如下:

 com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.163.com , 25; timeout -1;

原因:无法连接到163服务器,可能是spring.mail.host=smtp.163.com写错(后面多了一个空格,导致无法连接)

3、springboot启动报错:

Description:

Field mailService in com.activiti.spm.controller.MailController required a bean of type 'com.activiti.spm.service.MailService' that could not be found.

Action:

Consider defining a bean of type 'com.activiti.spm.service.MailService' in your configuration.

原因:Controller中调用Service,找不到指定的Service类

解决方式:在Service的实现类Impl中添加注解:@Service

Description:

Binding to target org.springframework.boot.autoconfigure.mail.MailProperties@2e27a93c failed:

    Property: spring.mail.defaultEncoding
    Value: UTF-8  
    Reason: Failed to convert property value of type 'java.lang.String' to required type 'java.nio.charset.Charset' for property 'defaultEncoding'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.nio.charset.Charset]


Action:

Update your application's configuration

原因:application.properties中配置出错,仔细检查,可能是配置后面有空格

4、发送html邮件格式出错,就是我们的html标签读取失败:


原因:可能是java代码编写错误:

错误写法:

helper.setText(content,true);

正确写法:

helper.setText(content,true);
完整方法如下:
public void sendHtmlMail(String to ,String subject,String content){
	MimeMessage message = mailSender.createMimeMessage();
	try{
		MimeMessageHelper helper = new MimeMessageHelper(message,true);
		helper.setFrom(from);
		helper.setTo(to);
		helper.setSubject(subject);
		helper.setText(content,true);
		mailSender.send(message);
		logger.info("html邮件发送成功!");
	}catch(MessagingException  e){
		logger.info("html邮件发送失败!"+e);
	}
}

注:本文参考:http://www.ityouknow.com/springboot/2017/05/06/springboot-mail.html

猜你喜欢

转载自blog.csdn.net/zz2713634772/article/details/79576930
今日推荐