邮件发送功能,QQ邮箱为例(javaMail)

一、获取QQ邮箱授权码(QQ邮箱-设置-账户-POP3/SMTP服务开启,发送验证短信后即可获取,注意保存授权码)

QQ邮箱服务

二、pom.xml导入相关依赖

我在这有用thymeleaf模板作为邮件发送模板所以要导入thymeleaf依赖

		<!-- email邮件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>

        <!-- thymeleaf模板 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.1.7.RELEASE</version>
        </dependency>

在这里贴上邮件的thymeleaf模板,CSS样式可以自己定义;
成功引用emailTemplate.html模板文件需要在配置文件中配置thymeleaf路径。(下面yml配置文件中有)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <style type="text/css">
        css代码自定义
    </style>
</head>
<body>
<div class="content">
    <div class="content-box">
        <div class="content-header">节日祝贺</div>
        <div class="content-text">您好!在这美好的节日之际,祝您:</div>
        <div class="content-code" th:text="${content}"></div>
    </div>
</div>
</body>
</html>

三、application.yml配置文件中配置email和thymeleaf

# Spring配置
spring:
  # QQ邮箱发送配置
  mail:
    # host不配置会注入失败
    host: smtp.qq.com
    username: 111111111@qq.com #自己的邮箱
    password: edrgrlcwtuhcbhfb #授权码
    default-encoding: utf-8
    protocol: smtp
    properties:
      mail:
        smtp:
          connectiontimeout: 5000
          timeout: 3000
          writetimeout: 5000
          ssl:
            enable: true #一定要开启ssl,不然会503 验证失败的(开启加密验证)
  # 模板
  thymeleaf:
    # 禁用缓存
    cache: false
    prefix: classpath:/templates/
    suffix: .html
    encoding: UTF-8
    mode: HTML
    servlet:
      content-type: text/html

四、写一个邮件发送的接口实现业务功能

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@RestController
@RequestMapping("/system/mail")
public class MailController {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

    //这一步是获取application.yml中设置的发件人邮箱地址
    @Value("${spring.mail.username}")
    private String username;
    

    /**
     * 群发,发送邮件模板
     * @param department
     * @return true/false
     * @throws MessagingException
     */
    @RequestMapping("/sendEmail")
    public AjaxResult sendEmail(String department, String content) throws MessagingException {
        try {
            //发邮件(创建javaMail实例)
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            // 第二个参数true表示使用HTML语言来编写邮件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            //发件人邮件地址(在上面从yml配置中获取的,也可以直接填写,string类型)
            helper.setFrom(username);
            //获取收件人邮件地址 在这里可以通过查询获取数据库中的邮箱
            Object arr[] = {"111111@qq.com","121212@qq.com","2222222@qq.com"};
            //Object arr[] = RsEmailService.selectEmail(department).toArray();
            //创建InternetAddress对象数组
            InternetAddress[] sendTo = new InternetAddress[arr.length];
            //遍历向对象数组追加
            for (int i = 0; i < arr.length; i++) {
                //System.out.println(arr[i]);
                sendTo[i] = new InternetAddress((String) arr[i]);
            }
            //设置收件人(密送,暗送;不显示收件人)
            mimeMessage.setRecipients(Message.RecipientType.BCC, sendTo);
            
            //设置收信人(会显示出多个收件人)
            //mimeMessage.setRecipients(Message.RecipientType.TO, sendTo);
            
			//设置抄送人
            //mimeMessage.setRecipients(Message.RecipientType.CC, sendTo);

            //单人单条发送
            //helper.setTo(email);

            //邮件主题
            helper.setSubject("节日推送");
            //使用模板thymeleaf
            //Context是导这个包import org.thymeleaf.context.Context;
            Context context = new Context();
            //设置传入模板的页面的参数 参数名为:content 参数随便写就行
            context.setVariable("content", content);
            //emailTemplate是要发送的模板,这里用的是Thymeleaf模板
            String emailContent = templateEngine.process("emailTemplate", context);
            //邮件正文(HTML模板)
            helper.setText(emailContent, true);
            //调用send方法发送邮件
            javaMailSender.send(mimeMessage);
            return AjaxResult.success("发送成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("发送失败!");
        }
    }
}
如果出现JavaMailSender自动注入失败的问题,有可能是配置文件的问题是:
  1. 配置文件没有email相关配置,
  2. 配置文件错误,需要注意配置文件的配置格式,邮箱账号和授权码的是否对应,以及对应邮箱的类型(不同的邮箱有不同主机(host)类型QQ邮箱的是:smtp.qq.com;其他类型可以自行查找)
注入失败的报错:

Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name ‘MailController’:
Unsatisfied dependency expressed through field ‘senderMail’;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type ‘org.springframework.mail.javamail.JavaMailSender’ available:
expected at least 1 bean which qualifies as autowire candidate. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}

没有问题后测试一下

邮件发送测试

成功收到邮件↓

收到邮件
完成以上流程,简单的邮件发送就实现了,另外可以根据需求设置选择发件人,查询获取用户邮箱进行批量发送。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用JavaMail下载QQ发送的附件,您需要进行以下步骤: 1. 首先,您需要获得QQ的POP3和SMTP服务器地址。您可以在QQ邮箱的设置中找到这些信息。 2. 然后,您需要使用JavaMail API连接到QQ邮箱的POP3服务器。这将允许您检索邮件和附件。以下是一个示例代码片段,演示如何连接到QQ邮箱的POP3服务器: ``` Properties props = new Properties(); props.setProperty("mail.store.protocol", "pop3"); props.setProperty("mail.pop3.host", "pop.qq.com"); props.setProperty("mail.pop3.port", "995"); props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); Session session = Session.getDefaultInstance(props); Store store = session.getStore(); store.connect("username@qq.com", "password"); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); Message[] messages = inbox.getMessages(); ``` 3. 接下来,您需要从邮件中提取附件。以下是一个示例代码片段,演示如何提取邮件中的附件: ``` for (Message message : messages) { Multipart multipart = (Multipart) message.getContent(); for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) { InputStream inputStream = bodyPart.getInputStream(); // 将 inputStream 写入文件或进行其他操作 } } } ``` 请注意,此示例代码仅提供参考。具体实现可能因您的具体情况而异。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值