SpringBoot+QQ邮箱实现邮件发送服务(纯文本邮件and带附件的邮件)

在实际开发中,邮件发送服务是网站的必备功能之一,例如用户注册验证、忘记密码、给用户发送营销信息等。在早期开发过程中,开发人员通常会使用JavaMail相关API实现邮件发送功能,后来Spring推出JavaMailSender简化了邮件发送的过程和实现,springBoot框架对Spring 提出的邮件发送服务也进行了整合支持。下面我们就针对springBoot框架整合支持的邮件任务进行实现。

1.SpringBoot邮件发送服务

1.1导包

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

1.2 配置SpringBoot全局文件

登录QQ邮箱,设置-账户-开启服务:POP3/SMTP服务
在这里插入图片描述
开启“POP3/SMTP服务”,获得的授权码为下面spring.mail.password的值。

#发件人邮箱服务器相关配置
## QQ邮箱固定以下配置
spring.mail.host=smtp.qq.com
spring.mail.port=587
#配置个人QQ账号和密码(密码是加密后的授权码)
## 你的邮箱账号
spring.mail.username=666677788@qq.com
## QQ邮箱开启POP3/SMTP服务后的授权码
spring.mail.password=rbnftozzextzbbea
spring.mail.default-encoding=utf-8
#邮件服务超时时间配置
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000

1.3 新建邮件发送Service

在service下新建两个接口,一个是发送纯文本邮件,一个是发送带附件的邮件:

public interface EmailSendService {

    //纯文本邮件信息发送
    public boolean sendSimpleEmail(String toEmailAddress, String subject, String text);

    //带附件邮件信息发送
    public boolean sendAttachmentEmail(String toEmailAddress, String subject, String text, String filePath);

}

创建serviceImpl:

package cn.com.***;

import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
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.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Component
@Slf4j
public class EmailSendServiceImpl implements EmailSendService {

    @Autowired
    private JavaMailSenderImpl mailSender;

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

    /**
     *
     * @param toEmailAddress 收件人地址
     * @param subject  邮件主题
     * @param text  邮件内容
     * @return 发送成功true
     */
    public boolean sendSimpleEmail(String toEmailAddress, String subject, String text){
        //定制纯文本邮件信息SimpleMailMessage
        SimpleMailMessage message=new SimpleMailMessage();
        try {
            message.setFrom(fromEmailAddress);  //设置发件箱
            message.setTo(toEmailAddress);  //设置收件箱
            message.setSubject(subject);  //设置邮件主题
            message.setText(text);  //设置邮件内容
            mailSender.send(message);  //调用Java封装好的发送方法
            return true;
        }catch (Exception e){
            log.debug("文本邮件发送失败");
            throw new BizException(e.toString());
        }
    }

    /**
     *
     * @param toEmailAddress 收件人地址
     * @param subject  邮件主题
     * @param text  邮件内容
     * @param filePath 附件本地路径
     * @return 发送成功true
     */
    public boolean sendAttachmentEmail(String toEmailAddress, String subject, String text, String filePath){
        //定制复杂邮件信息MimeMessage
        MimeMessage message=mailSender.createMimeMessage();
        try {
            //使用MimeMessageHelper帮助类,并设置multipart多部件使用为true。帮助将邮件信息封装到MimeMessage message中
            MimeMessageHelper helper=new MimeMessageHelper(message,true);
            helper.setFrom(fromEmailAddress);  //设置发件箱
            helper.setTo(toEmailAddress);   //设置收件箱
            helper.setSubject(subject);  //设置邮件主题
            helper.setText(text,true);  //设置邮件内容
            //设置邮件静态资源
            //FileSystemResource res=new FileSystemResource(new File(rscPath));
            //helper.addInline(rscId, res);
            //设置附件地址
            FileSystemResource file=new FileSystemResource(new File(filePath));
            String fileName=filePath.substring(filePath.lastIndexOf(File.separator));  //也可以自己命名
            helper.addAttachment(fileName, file);
            //发送邮件
            mailSender.send(message);
            log.debug("复杂邮件发送成功");
            return true;
        } catch (MessagingException e) {
            log.debug("复杂邮件发送失败。。。。。。");
            throw new BizException(e.toString());
        }

    }
}

调用上面接口就可以实现邮件发送啦

Tips

邮件内容是简单的String文本的话,字体样式布局为邮件默认的样式。
如果想实现自定义邮件文本主题样式,可以将邮件内容text采用以下方式写入:

//定义带格式的邮件内容
		 StringBuilder  text = new StringBuilder();
		 text.append("<html><head></head>");
		 text.append("<body><h1>祝大家新年快乐!</h1>");
		 text.append("********恭喜发财*********</body>");
		 text.append("</html>");
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是使用Spring Boot发送邮件的步骤: 1. 导入Spring Boot提供的依赖[^1]: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 2. 在配置文件中设置邮箱信息: ```properties spring.mail.host=smtp.qq.com spring.mail.port=587 spring.mail.username=your-email@qq.com spring.mail.password=your-email-password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` 3. 创建一个邮件服务类,用于发送邮件[^2]: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service public class EmailService { @Autowired private JavaMailSender mailSender; public void sendEmail(String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); mailSender.send(message); } } ``` 4. 在需要发送邮件的地方调用邮件服务类的方法发送邮件: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class EmailController { @Autowired private EmailService emailService; @GetMapping("/sendEmail") public String sendEmail() { String to = "recipient@example.com"; String subject = "Test Email"; String text = "This is a test email."; emailService.sendEmail(to, subject, text); return "Email sent successfully."; } } ``` 以上是使用Spring Boot发送邮件的简单示例。你可以根据自己的需求进行相应的配置和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值