25、springboot发送邮件

38 篇文章 0 订阅
27 篇文章 3 订阅

虽然现在短信验证已经最流行也是最常用的验证方式;但是邮件验证还是必不可少,依然是网站的必备功能之一。什么注册验证,忘记密码或者是给用户发送营销信息都是可以使用邮件发送功能的。最早期使用JavaMail的相关api来进行发送邮件的功能开发,后来spring整合了JavaMail的相关api推出了JavaMailSender更加简化了邮件发送的代码编写,现在springboot对此进行了封装就有了现在的spring-boot-starter-mail。

1、 新建项目sc-mail,对应的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>spring-cloud</groupId>
	<artifactId>sc-mail</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>sc-mail</name>
	<url>http://maven.apache.org</url>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.4.RELEASE</version>
	</parent>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Finchley.RELEASE</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>

		</dependencies>
	</dependencyManagement>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

	<dependencies>

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


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

	</dependencies>
</project>

2、 新建配置文件application.yml

spring:
  application:
    name: sc-mail
  mail:
    host: smtp.qq.com #邮箱服务器地址
    port: 465
    username: 515768476@qq.com #用户名
    password: vfcqhwsnnwugbhcx #密码 (改成自己的密码)
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          ssl:
            enable:
              true

3、 新建邮件发送服务类

package sc.mail.service.impl;

import java.io.File;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.Service;

import sc.mail.service.MailService;

@Service
public class MailServiceImpl implements MailService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private JavaMailSender mailSender;

	/**
	 * 文本
	 * @param from
	 * @param to
	 * @param subject
	 * @param content
	 */
	@Override
	public void sendSimpleMail(String from, 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);
			logger.info("simple mail had send。");
		} catch (Exception e) {
			logger.error("send mail error", e);
		}
	}

	/**
	 * @param from
	 * @param to
	 * @param subject
	 * @param content
	 */
	public void sendTemplateMail(String from, String to, String subject, String content) {
	    MimeMessage message = mailSender.createMimeMessage();
	    try {
	        //true表示需要创建一个multipart message
	        MimeMessageHelper helper = new MimeMessageHelper(message, true);
	        helper.setFrom(from);
	        helper.setTo(to);
	        helper.setSubject(subject);
	        helper.setText(content, true);
	        mailSender.send(message);
	        logger.info("send template success");
	    } catch (Exception e) {
	        logger.error("send template eror", e);
	    }
	}
	
	
	/**
	 * 附件
	 * 
	 * @param from
	 * @param to
	 * @param subject
	 * @param content
	 * @param filePath
	 */
	public void sendAttachmentsMail(String from, 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);
	        mailSender.send(message);
	        logger.info("send mail with attach success。");
	    } catch (Exception e) {
	        logger.error("send mail with attach success", e);
	    }
	}
	
	
	/**
	 * 发送内嵌图片
	 * 
	 * @param from
	 * @param to
	 * @param subject
	 * @param content
	 * @param imgPath
	 * @param imgId
	 */
	public void sendInlineResourceMail(String from, String to, String subject, String content,
			String imgPath, String imgId){
	    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 res = new FileSystemResource(new File(imgPath));
	        helper.addInline(imgId, res);
	        mailSender.send(message);
	        logger.info("send inner resources success。");
	    } catch (Exception e) {
	        logger.error("send inner resources fail", e);
	    }
	}

}

4、 新建测试类

package sc.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;

import sc.mail.service.MailService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MailSendTest {

	@Autowired
	private MailService mailService;

	@Test
	public void sendSimpleMailTest() {
		mailService.sendSimpleMail("515768476@qq.com", "happy.huangjinjin@163.com", 
				"sendSimpleMailTest", "sendSimpleMailTest from 515768476@qq.com");
	}

	@Test
	public void sendTemplateMailTest() {
		String html = "<html><body>"
				+ " <div> "
				+ "    sendTemplateMailTest from 515768476@qq.com </br>"
				+ "    <b>这是模板邮件</b>"
				+ "</div>"
				+ "</body></html>";
		mailService.sendTemplateMail("515768476@qq.com", "happy.huangjinjin@163.com", 
				"sendTemplateMailTest", html);
	}

	@Test
	public void sendAttachmentsMailTest() {
		String filePath = "D:\\springcloudws\\sc-mail\\src\\main\\java\\sc\\mail\\service\\impl\\MailServiceImpl.java";
		mailService.sendAttachmentsMail("515768476@qq.com", "happy.huangjinjin@163.com", 
				"sendAttachmentsMailTest", "sendAttachmentsMailTest from 515768476@qq.com", filePath);
	}
	
	@Test
	public void sendInlineResourceMailTest() {
		String imgId = "img1";
		
		String content = "<html><body>"
				+ "sendInlineResourceMailTest:<img src=\'cid:" + imgId + "\' >"
						+ "</body></html>";
		
		String imgPath = "D:\\springcloudws\\sc-mail\\src\\main\\resources\\20181015223228.jpg";
		
		mailService.sendInlineResourceMail("515768476@qq.com", "happy.huangjinjin@163.com", 
				"sendAttachmentsMailTest", content, imgPath, imgId);
	}

}

5、 运行测试类验证是否发送邮件成功
登录happy.huangjinjin@163.com邮箱
在这里插入图片描述
简单邮件
在这里插入图片描述
模板邮件
在这里插入图片描述
附件邮件
在这里插入图片描述
内嵌图片邮件

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
适用人群通用各大网易系,腾讯QQ系,新浪系,阿里系等主流邮箱;同时也适用于企业开发的企业邮箱,进行收件和发件。课程概述通用各大网易系,腾讯QQ系,新浪系,阿里系等主流邮箱;同时也适用于企业开发的企业邮箱,进行收件和发件。POP3是Post Office Protocol 3的简称,即邮局协议的第3个版本,它规定怎样将个人计算机连接到Internet的邮件服务器和下载电子邮件的电子协议。它是因特网电子邮件的第一个离线协议标准,POP3允许用户从服务器上把邮件存储到本地主机(即自己的计算机)上,同时删除保存在邮件服务器上的邮件,而POP3服务器则是遵循POP3协议的接收邮件服务器,用来接收电子邮件的SMTP 的全称是“Simple Mail Transfer Protocol”,即简单邮件传输协议。它是一组用于从源地址到目的地址传输邮件的规范,通过它来控制邮件的中转方式。SMTP 协议属于 TCP/IP 协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。SMTP 服务器就是遵循 SMTP 协议的发送邮件服务器。   SMTP 认证,简单地说就是要求必须在提供了账户名和密码之后才可以登录 SMTP 服务器,这就使得那些垃圾邮件的散播者无可乘之机。。【开发者如何进行快速开发邮件发送系统???本课程系统进行快速研发,项目实战】 部分截图如下:完整版请查看课件或者视频
以下是使用SpringBoot发送邮件的示例代码,其中包括了如何发送带附件的邮件和如何开启TLS验证: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.mail.MailProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @SpringBootApplication @EnableConfigurationProperties(MailProperties.class) public class MailApplication { @Autowired private JavaMailSender mailSender; @Autowired private MailProperties mailProperties; public static void main(String[] args) { SpringApplication.run(MailApplication.class, args); } public void sendMailWithAttachment() throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(mailProperties.getUsername()); helper.setTo("recipient@example.com"); helper.setSubject("Test email with attachment"); // 添加附件 FileSystemResource file = new FileSystemResource(new File("attachment.txt")); helper.addAttachment("attachment.txt", file); // 发送邮件 mailSender.send(message); } } ``` 在application.properties文件中添加以下配置: ``` spring.mail.username=xxxxxxx@outlook.com spring.mail.password=xxxxxxxxx spring.mail.port=587 spring.mail.host=smtp-mail.outlook.com spring.mail.properties.mail.smtp.starttls.required=true ``` 注意:在使用Outlook发送邮件时,需要开启TLS验证,否则会显示匿名用户无法通过验证。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BUG弄潮儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值