springboot2.0 快速开发邮件发送

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ljk126wy/article/details/83239398

首先访问springboot 官方文档查看如何进行邮件发送相关开发,这里看的是2.0.6版本的文档,但是我们的demo则是采用 2.0.5 进行介绍。前些天还看的是2.0.5 最近发现官网最新的是2.0.6 啦 但是使用方式基本一致啦。文档地址:https://docs.spring.io/spring-boot/docs/2.0.6.RELEASE/reference/htmlsingle/#boot-features-email    spring 为发送邮件功能提供啦一个JavaMailSender 接口帮我们来实现邮件的发送。同时提供啦mail 的start 依赖 。我们可以通过spring 提供的如何使用详细文档继续查看。https://docs.spring.io/spring/docs/5.0.10.RELEASE/spring-framework-reference/integration.html#mail

1 邮件功能开发准备

我们这里不对官网内容做过多的阐述,直接上代码啦。第一个先引入mail 的start 依赖。

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

spirngboot mail 需要添加的配置信息 我们这里是通过yml 方式进行配置

spring:
  mail:
    host: smtp.126.com
    username: 邮箱用户名
    password: 邮箱密码
    properties:
      mail:
        smtp:
          auth: true  # 需要验证登录名和密码
        starttls:
          enable: true  # 需要TLS认证 保证发送邮件安全验证
          required: true

2 发送普通的邮件

接下来就是我们们邮件发送demo的正式编写啦。spirng对发送邮件功能进行啦封装。 在使用的时候我们只需要定义发送信息到SimpleMailMessage 中 然后通过 JavaMailSender 的send 方法进行发送即可。

package cn.lijunkui.mail;

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.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class MailService {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
    @Autowired
    private JavaMailSender sender;
    
    @Value("${spring.mail.username}")
    private String formMail;
    
    public void sendSimpleMail(String toMail,String subject,String content) {
    	 SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
    	 simpleMailMessage.setFrom(formMail);
         simpleMailMessage.setTo(toMail);
         simpleMailMessage.setSubject(subject);
         simpleMailMessage.setText(content);
         try {
             sender.send(simpleMailMessage);
             logger.info("发送给"+toMail+"简单邮件已经发送。 subject:"+subject);
         }catch (Exception e){
             logger.info("发送给"+toMail+"send mail error subject:"+subject);
             e.printStackTrace();
         }
    }
}

编写测试用例:

在开发中建议大家将每个编写完的小功能进行测试 养生良好的开发习惯。

package cn.lijunkui.mail;

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;

@SpringBootTest
@RunWith(SpringRunner.class)
public class MailServiceTest {
	@Autowired
	private MailService mailService;
	
	@Test
	public void sendSimpleMail() {
		mailService.sendSimpleMail("[email protected]", "这是一个测试邮件", "这是一个测试邮件");
	}
	
}

 测试结果:

3 发送html格式邮件 

开发步骤:

1 通过JavaMailSender的createMimeMessage() 创建MimeMessage  对象实例

2 通过 将 MimeMessage 放入到MimeMessageHelper  构造函数中,并在 MimeMessageHelper设置发送邮件信息 包括 发送人 被发送人 主题 内容以及是否是用html

3 通过JavaMailSender 发送 MimeMessageHelper

    public void sendHtmlMail(String toMail,String subject,String content) {
    	 MimeMessage mimeMessage = sender.createMimeMessage();
    	 try {
			MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
			mimeMessageHelper.setTo(toMail);
			mimeMessageHelper.setFrom(formMail);
			mimeMessageHelper.setText(content,true);
			mimeMessageHelper.setSubject(subject);
			sender.send(mimeMessage);
			 logger.info("发送给"+toMail+"html邮件已经发送。 subject:"+subject);
		} catch (MessagingException e) {
			 logger.info("发送给"+toMail+"html send mail error subject:"+subject);
			e.printStackTrace();
		}
    }
	@Test
	public void snedHtmlMail() {
		String html= "<!DOCTYPE html>\r\n" + 
				"<html>\r\n" + 
				"<head>\r\n" + 
				"<meta charset=\"UTF-8\">\r\n" + 
				"<title>Insert title here</title>\r\n" + 
				"</head>\r\n" + 
				"<body>\r\n" + 
				"	<font color=\"red\">发送html</font>\r\n" + 
				"</body>\r\n" + 
				"</html>";
		mailService.sendHtmlMail("[email protected]", "这是一个测试邮件", html);
	}

4 发送html 中带图片的邮件

发送html中带图片的邮件和上面发送html邮件内容基本一致,多了一步通过MimeMessageHelper addInline 的方法

1 我们在定义html 内容是嵌入的image src 内容中制定cid 例如 <img src=\"cid:image1\"/>

2 在设置MimeMessageHelper通过addInline 将cid 和文件资源进行指定即可

package cn.lijunkui.mail;

public class InlineResource {
	private String cid;
	private String path;
	public String getCid() {
		return cid;
	}
	public void setCid(String cid) {
		this.cid = cid;
	}
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public InlineResource(String cid, String path) {
		super();
		this.cid = cid;
		this.path = path;
	}
}
    /**
     * 发送静态资源(一般是图片)的邮件
     * @param to
     * @param subject
     * @param content 邮件内容,需要包括一个静态资源的id,比如:<img src=\"cid:image\" >
     * @param resourceist 静态资源list
     */
    public void sendInlineResourceMail(String to, String subject, String content,List<InlineResource> resourceist){
        MimeMessage message = sender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(formMail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            for (InlineResource inlineResource : resourceist) {
            	FileSystemResource res = new FileSystemResource(new File(inlineResource.getPath()));
            	  helper.addInline(inlineResource.getCid(),res);
			}
            sender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送嵌入静态资源的邮件时发生异常!", e);
        }
    }
	@Test
	public void sendInlineResourceMail() {
		String html= "<!DOCTYPE html>\r\n" + 
				"<html>\r\n" + 
				"<head>\r\n" + 
				"<meta charset=\"UTF-8\">\r\n" + 
				"<title>Insert title here</title>\r\n" + 
				"</head>\r\n" + 
				"<body>\r\n" + 
				"<img src=\"cid:image1\"/> "+
				"<img src=\"cid:image2\"/> "+
				"	<font color=\"red\">发送html</font>\r\n" + 
				"</body>\r\n" + 
				"</html>";
		List<InlineResource> list = new ArrayList<InlineResource>();
		String path = MailServiceTest.class.getClassLoader().getResource("image.jpg").getPath();
		
		InlineResource resource = new InlineResource("image1",path);
		InlineResource resource2 = new InlineResource("image2",path);
		
		list.add(resource2);
		list.add(resource);
		mailService.sendInlineResourceMail("[email protected]", "这是一个测试邮件", html,list);
	}

4 发送带附件的邮件 

发送带附件的邮件和发送html 也是基本一致的,通过在通过MimeMessageHelper设置邮件信息的时候,将附件信息FileSystemResource 通过 MimeMessageHelper  addAttachment 设置到发送邮件信息中即可。

    public void sendAttachmentsMail(String toMail,String subject,String content,String filePath) {
    	 MimeMessage message = sender.createMimeMessage();
         try {
             MimeMessageHelper helper = new MimeMessageHelper(message, true);
             helper.setFrom(formMail);
             helper.setTo(toMail);
             helper.setSubject(subject);
             helper.setText(content, true);
             FileSystemResource file = new FileSystemResource(new File(filePath));
             String fileName = filePath.substring(filePath.lastIndexOf("/"));
             helper.addAttachment(fileName, file);
             sender.send(message);
             logger.info("发送给"+toMail+"带附件的邮件已经发送。");
         } catch (MessagingException e) {
             e.printStackTrace();
             logger.error("发送给"+toMail+"带附件的邮件时发生异常!", e);
         }
     }

测试用例:

	@Test
	public void sendAttachmentsMail() {
		String html= "<!DOCTYPE html>\r\n" + 
				"<html>\r\n" + 
				"<head>\r\n" + 
				"<meta charset=\"UTF-8\">\r\n" + 
				"<title>Insert title here</title>\r\n" + 
				"</head>\r\n" + 
				"<body>\r\n" + 
				"	<font color=\"red\">发送html</font>\r\n" + 
				"</body>\r\n" + 
				"</html>";
		String path = MailServiceTest.class.getClassLoader().getResource("image.jpg").getPath();
		mailService.sendAttachmentsMail("[email protected]", "这是一个测试邮件", html, path);
	}

 

猜你喜欢

转载自blog.csdn.net/ljk126wy/article/details/83239398