springboot发送邮件

一.邮件发送原理
(一)邮件传输协议
SMTP协议:底层邮件系统,将邮件由一台服务器传送至多台服务器
POP3协议:邮件访问标准协议第三版本,可以将邮件下载到本地
IMAP协议:交互式邮件协议,对pop3协议的补充
Mime协议:编码二进制协议
(二)邮件发送流程

在这里插入图片描述
三.代码
(一)依赖

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

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>

(二)test

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 javax.annotation.Resource;
import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.Map;


@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailTest {
    @Resource
    private EmailService emailService;
    @Autowired
    private TemplateEngine templateEngine;

    //发送简单文件
    @Test
    public void sendSimpleEmail() {
        emailService.sendSimpleMail("xx.qq.com", "lms", "lms");
    }


    //发送HTML邮件
    @Test
    public void sendHtmlEmail() throws MessagingException {
        String content = "<html>\n" +
                "<body>\n" +
                "<h3>html邮件</h3>\n" +
                "</body>\n" +
                "<html>";
        emailService.sendHtmlMail("xx.qq.com", "html", content);
    }

    //发送带附件的邮件
    @Test
    public void sendAttachmentsMail() throws MessagingException {
        String content = "<html>\n" +
                "<body>\n" +
                "<h3>嘻嘻</h3>\n" +
                "</body>\n" +
                "<html>";
        String filePath = "C:\\Users\\Administrator\\Desktop\\图片\\aa.jpg";
        emailService.sendAttachmentsMail("xx.qq.com", "带附件的html邮件", content, filePath);
    }

    //发送带图片的邮件
    @Test
    public void sendInlineResourceMail() throws MessagingException {

        Map<String, String> srcMap = new HashMap<>();
        String imgPath1 = "C:\\Users\\Administrator\\Desktop\\图片\\timg.jpg";
        String imgPath2 = "C:\\Users\\Administrator\\Desktop\\图片\\mimi.jpg";
        String srcId1 = "001";
        String srcId2 = "002";
        srcMap.put(srcId1, imgPath1);
        srcMap.put(srcId2, imgPath2);
        StringBuilder imgStr = new StringBuilder();
        for (String srcKey : srcMap.keySet()) {
            imgStr.append("<img src=\'cid:" + srcKey + "\'/>\n");
        }
        String content = "<html>\n" +
                "<body>\n" +
                "<h1>这是带图片的邮件</h1>\n" +
                imgStr +
                "</body>\n" +
                "<html>";
        emailService.sendInlineResourceMail("xx.qq.com", "带附件的html邮件", content, srcMap);
    }

    //发送模板邮件
    @Test
    public void testTemplate() throws MessagingException {
        Context context = new Context();
        context.setVariable("id","12345");
        String emailContent = templateEngine.process("emailTemplate", context);
        emailService.sendHtmlMail("xx.qq.com", "模板邮件", emailContent);
    }
}

(三)service

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.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;


@Service
public class EmailService {
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private JavaMailSender mailSender;

    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);
        mailSender.send(message);
    }
    public void sendHtmlMail(String to,String subject,String content) throws MessagingException {
        MimeMessage message=mailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(message,true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content,true);
        mailSender.send(message);
    }

    public void sendAttachmentsMail(String to,String subject,String content,String filePath) throws MessagingException {
        MimeMessage message=mailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(message,true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content,true);
        //添加附件,可上传多个
        FileSystemResource file=new FileSystemResource(filePath);
        String fileName=file.getFilename();
        helper.addAttachment(fileName,file);
        helper.addAttachment(fileName+"_test",file);
        mailSender.send(message);
    }

    public void sendInlineResourceMail(String to, String subject, String content,
                                       Map<String,String> srcMap) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content,true);
        for (String srcKey:srcMap.keySet()){
            FileSystemResource res = new FileSystemResource(srcMap.get(srcKey));
            helper.addInline(srcKey,res);
        }

        mailSender.send(message);
    }

}

(四)配置文件

spring.mail.host=smtp.qq.com
spring.mail.username=XX@qq.com
spring.mail.password=qq的授权证
spring.mail.default-encoding=utf-8
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值