基于SpringBoot实现复杂邮件信息发送

本文详细介绍了如何在SpringBoot项目中配置和使用JavaMailSender发送简单邮件和带有附件的邮件,包括设置SMTP服务器、编写控制器和测试步骤。
摘要由CSDN通过智能技术生成

基于SpringBoot实现简单/复杂邮件信息发送

1.进入qq邮箱,点击设置

在这里插入图片描述

2.点击账号

在这里插入图片描述

3.找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,点击开启服务

在这里插入图片描述

4.发送验证码验证一下,复制验证码

在这里插入图片描述

5.进入idea,引入依赖

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

6.编写配置文件

spring:
  mail:
    default-encoding: utf-8
    # 主机地址
    host: smtp.qq.com
    # 邮箱名,改成你的
    username: xxxxxxxxxx@qq.com
    # 授权码(不是密码),上面复制的授权码
    password: xxxxxxxx

7.编写controller,这里代码比较简单,我没有分层

@RestController
public class EmailController {

    @Autowired
    private JavaMailSender mailSender;
    //简单发送
    @GetMapping("/send1")
    //里面可以将邮件内容作为标题
    private void send(){
        SimpleMailMessage message = new SimpleMailMessage();
        // 发件人,改为你的邮箱
        message.setFrom("xxxxxxxxxx@qq.com");
        // 收件人,改为目标邮箱
        message.setTo("xxxxxxxxxx@qq.com");
        // 邮件标题
        message.setSubject("测试标题");
        // 邮件内容
        message.setText("测试内容");
        // 抄送人
        //message.setCc("xxx@qq.com");
        mailSender.send(message);
    }
    
    //文件发送
    @PostMapping("/send2")
    public void sendEmailWithAttachment(String recipient, String subject, String text, String attachmentPath) {
        //由于没有前端页面,参数就写死了!!!
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
		   //改为接受的qq邮箱
            recipient = "xxxxxxxxxx@qq.com";
            subject = "测试主题";
            text = "测试内容";
            attachmentPath = "C:\\Users\\Administrator\\Desktop\\test.txt";

            helper.setFrom("xxxxxxxxxx@qq.com");
            helper.setTo(recipient);
            helper.setSubject(subject);
            helper.setText(text);
            // 添加附件
            File attachment = new File(attachmentPath);
            helper.addAttachment(attachment.getName(), attachment);

            mailSender.send(message);

            System.out.println("Email with attachment sent successfully!");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.err.println("Failed to send email with attachment.");
        }
    }
}

8.启动测试,浏览器输入http://localhost:8080/send1

end email with attachment.");
}
}
}


8.启动测试,浏览器输入http://localhost:8080/send1

注意,浏览器是get请求,send2要去postman或者其他的测试软件!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值