美文网首页
springboot常用starter⑯-mail

springboot常用starter⑯-mail

作者: 一个好汉 | 来源:发表于2021-07-21 23:03 被阅读0次

电子协议

常用的电子邮件协议有

  • SMTP
  • POP3
  • IMAP4

以上都隶属于TCP/IP协议簇
默认状态下,分别通过TCP端口25、110和143建立连接

其实一般每个提供电子邮件服务的网站都有自己的 SMTP 和 POP 服务器地址
登录你的电子邮件网站就可以找到它 一般是在帮助里面

POP3

POP3(邮局通讯协定)
用在传送电子邮件
邮件服务器必须为收信者保存这封信,直到收信者来检查这封信件
当收信人收信的时候,必须通过 POP 通讯协定,才能取得邮件

SMTP

SMTP(简易邮件传输通讯协议)
用来传送网络上的电子邮件
SMTP 负责邮件服务器与邮件服务器之间的寄信

集成mail

引入jar包

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

配置发送邮箱信息

######################邮件相关##################
# SMTP服务器地址
spring.mail.host=smtp.qq.com
# SMTP服务器端口号 默认-1
# spring.mail.port=-1
# 发送方帐号
spring.mail.username=1908711045@qq.com
# 发送方密码(授权码)
spring.mail.password=awpkocnlwuoddbdj
#javaMailProperties 配置
# 开启用户身份验证
spring.mail.properties.mail.smtp.auth=true
# STARTTLS:一种通信协议,具体可以搜索下
#spring.mail.properties.mail.smtp.starttls.enable=true
#spring.mail.properties.mail.smtp.starttls.required=true

使用

package cn.gd.cz.hong.springbootlearn.service.impl;

import cn.gd.cz.hong.springbootlearn.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 实现发送邮件
 */
@Service
public class MailServiceImpl implements MailService {

    @Resource
    private JavaMailSender mailSender;

    @PostConstruct
    public void init() {
        sendText("spring学习中");
    }

    @Override
    public void sendText(String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1908711045@qq.com");
        message.setTo("m15220004896@163.com");
        message.setSubject("test");
        message.setText(content);
        mailSender.send(message);
    }
}

mail不仅可以发送文本 还可以发送附件 HTML 甚至可以用freemaker制作模板

参考

POP3、SMTP和IMAP之间的区别和联系

mail

相关文章

网友评论

      本文标题:springboot常用starter⑯-mail

      本文链接:https://www.haomeiwen.com/subject/bcmmultx.html