Spring Boot mail

准备步骤

首先需要获取mail server的客户端授权码。

本例中使用的是搜狐邮箱,登录邮箱,点击“选项” -> “设置”:
在这里插入图片描述

在设置页面,点击 POP3/SMTP/IMAP
在这里插入图片描述
选中 POP3/SMTP/IMAP ,获取第三方客户端独立密码:
在这里插入图片描述
注:授权码是10个字符组成的一个字符串。

代码

set up project

新建Project “testmail”,在依赖关系中,选中“Web -> Spring Web”和“I/O -> Java Mail Sender”
在这里插入图片描述
application.properties 文件中添加如下代码:

spring.mail.host=smtp.sohu.com
spring.mail.username=duke_ding@sohu.com
spring.mail.password=<客户端授权码>
spring.mail.default-encoding=UTF-8

简单mail

Service 代码:

package com.example.testmail;

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 TestMailServiceImpl implements TestMailServiceIF{
    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setFrom(from);
        message.setSubject(subject);
        message.setText(content);

        mailSender.send(message);
    }
}

注: TestMailServiceIF 是自己定义的接口。

Controller代码:

package com.example.testmail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestMailController {
    @Autowired
    TestMailServiceIF service;

    @RequestMapping(value = "/sendsimplemail", method = RequestMethod.POST)
    public void sendSimpleMail(String to, String subject, String content) {
        service.sendSimpleMail(to, subject, content);
    }
}

运行:

➜  ~ curl --silent --write-out '\n%{http_code}\n' -XPOST "http://localhost:8080/sendsimplemail?to=duke_ding@sohu.com&subject=testmail&content=hello" | jq .
200

搜狐邮箱,收到mail如下:
在这里插入图片描述

HTML mail

Service 代码:

    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();

        String str = "<html><body><h1>" + content + "</h1></body></html>";
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(str, true);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        mailSender.send(message);
    }

Controller代码:

    @RequestMapping(value = "/sendhtmlmail", method = RequestMethod.POST)
    public void sendHtmlMail(String to, String subject, String content) {
        service.sendHtmlMail(to, subject, content);
    }

运行:

➜  ~ curl --silent --write-out '\n%{http_code}\n' -XPOST "http://localhost:8080/sendhtmlmail?to=duke_ding@sohu.com&subject=testhtmlmail&content=hello_html" | jq .
200

搜狐邮箱,收到mail如下:
在这里插入图片描述

带图片的mail

Service代码:

    @Override
    public void sendPictureMail(String to, String subject, String content, String resPath, String resId) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            String str = "<html><body>" + content + "<br><img width='250px' src=\'cid:" + resId + "\'></body></html>";
            helper.setText(str, true);
            File file = new File(resPath);
            FileSystemResource res = new FileSystemResource(file);
            helper.addInline(resId, res);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        mailSender.send(message);
    }

Controller代码:

    @RequestMapping(value = "/sendpicturemail", method = RequestMethod.POST)
    public void sendPictureMail(String to, String subject, String content, String respath, String resid) {
        service.sendPictureMail(to, subject, content, respath, resid);
    }

运行:

➜  ~ curl --silent --write-out '\n%{http_code}\n' -XPOST "http://localhost:8080/sendpicturemail?to=duke_ding@sohu.com&subject=testpicturemail&content=hello&respath=/home/ding/temp/spring.jpg&resid=aaa" | jq .
200

搜狐邮箱,收到mail如下:
在这里插入图片描述

带附件的mail

Service代码:

    @Override
    public void sendAttachmentMail(String to, String subject, String content, String resPath) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(resPath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        mailSender.send(message);
    }

Controller代码:

    @RequestMapping(value = "/sendattachmentmail", method = RequestMethod.POST)
    public void sendAttachmentMail(String to, String subject, String content, String respath) {
        service.sendAttachmentMail(to, subject, content, respath);
    }

运行:

➜  ~ curl --silent --write-out '\n%{http_code}\n' -XPOST "http://localhost:8080/sendattachmentmail?to=duke_ding@sohu.com&subject=testattachmentmail&content=hello_attachment&respath=/home/ding/temp/aaa.txt" | jq .
200

搜狐邮箱,收到mail如下:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个流行的Java框架,它简化了构建独立的、可运行的Spring应用程序的过程。Spring Boot EmailSpring Boot生态系统中的一个扩展模块,它提供了集成的电子邮件服务,使得在Spring Boot应用中发送电子邮件变得更加容易。 主要特点包括: 1. **自动配置**:Spring Boot Email通过自动配置功能,你可以通过简单的配置就能启用邮件发送功能,无需手动配置邮件服务器。 2. **支持多个邮件服务**:它支持使用JavaMail API连接到各种邮件服务器,如SMTP、IMAP等。 3. **模板引擎**:可以使用Thymeleaf、Velocity等模板引擎创建动态邮件内容。 4. **集成邮件验证**:有时用于用户激活或密码重置的邮件确认过程。 使用Spring Boot Email的步骤大致如下: - 添加依赖:在你的`pom.xml`文件中添加Spring Boot Email的Maven或Gradle依赖。 ```xml <!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <!-- Gradle --> implementation 'org.springframework.boot:spring-boot-starter-mail' ``` - 配置邮箱属性:在`application.properties`或`application.yml`中设置邮件服务器的相关信息,如主机名、端口、用户名和密码等。 ```properties spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=myusername spring.mail.password=mypassword spring.mail.protocol=smtp ``` - 发送邮件:通过`JavaMailSender`接口或`MessageSource`发送自定义邮件。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; @Autowired private JavaMailSender mailSender; public void sendEmail(String to, String subject, String body) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(body); mailSender.send(message); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值