springboot 邮件

本文详细介绍了SpringBoot如何配置并使用JavaMailSender发送邮件,包括配置邮件服务器参数、创建JavaMailSender实例、使用MimeMessageHelper设置邮件内容,并通过示例展示了发送邮件的完整流程。
摘要由CSDN通过智能技术生成

springboot 邮件

               

                        

*********************

相关类与接口

               

MailSenderAutoConfiguration:自动配置类

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnClass({MimeMessage.class, MimeType.class, MailSender.class})
@ConditionalOnMissingBean({MailSender.class})
@Conditional({MailSenderAutoConfiguration.MailSenderCondition.class})
@EnableConfigurationProperties({MailProperties.class})   //配置MailProperties属性实例
@Import({MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class})
                                    //导入 MailSenderPropertiesConfiguration配置类
public class MailSenderAutoConfiguration {
    public MailSenderAutoConfiguration() {
    }

    static class MailSenderCondition extends AnyNestedCondition {
        MailSenderCondition() {
            super(ConfigurationPhase.PARSE_CONFIGURATION);
        }

        @ConditionalOnProperty(
            prefix = "spring.mail",
            name = {"jndi-name"}
        )
        static class JndiNameProperty {
            JndiNameProperty() {
            }
        }

        @ConditionalOnProperty(
            prefix = "spring.mail",
            name = {"host"}
        )
        static class HostProperty {
            HostProperty() {
            }
        }
    }
}

                

MailProperties

@ConfigurationProperties(
    prefix = "spring.mail"
)
public class MailProperties {
    private static final Charset DEFAULT_CHARSET;
    private String host;
    private Integer port;
    private String username;
    private String password;
    private String protocol = "smtp";
    private Charset defaultEncoding;
    private Map<String, String> properties;
    private String jndiName;

    public MailProperties() {
        this.defaultEncoding = DEFAULT_CHARSET;
        this.properties = new HashMap();
    }

               

MailSenderPropertiesConfiguration

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnProperty(
    prefix = "spring.mail",
    name = {"host"}
)
class MailSenderPropertiesConfiguration {
    MailSenderPropertiesConfiguration() {
    }

    @Bean
    @ConditionalOnMissingBean({JavaMailSender.class})
    JavaMailSenderImpl mailSender(MailProperties properties) {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        this.applyProperties(properties, sender);
        return sender;
    }  //如果不存在JavaMailSender实例,则创建JavaMailSender实例

    private void applyProperties(MailProperties properties, JavaMailSenderImpl sender) {
        sender.setHost(properties.getHost());
        if (properties.getPort() != null) {
            sender.setPort(properties.getPort());
        }

        sender.setUsername(properties.getUsername());
        sender.setPassword(properties.getPassword());
        sender.setProtocol(properties.getProtocol());
        if (properties.getDefaultEncoding() != null) {
            sender.setDefaultEncoding(properties.getDefaultEncoding().name());
        }

        if (!properties.getProperties().isEmpty()) {
            sender.setJavaMailProperties(this.asProperties(properties.getProperties()));
        }

    }

    private Properties asProperties(Map<String, String> source) {
        Properties properties = new Properties();
        properties.putAll(source);
        return properties;
    }
}

                             

JavaMailSender

public interface JavaMailSender extends MailSender {

    MimeMessage createMimeMessage();
    MimeMessage createMimeMessage(InputStream var1) throws MailException;

    void send(MimeMessage var1) throws MailException;
    void send(MimeMessage... var1) throws MailException;
    void send(MimeMessagePreparator var1) throws MailException;
    void send(MimeMessagePreparator... var1) throws MailException;
}

                 

                      

*********************

示例

                

******************

application.yml

               

spring:
  mail:
    host: smtp.qq.com
    port: 465 #587
    protocol: smtps     #端口587,protocol设置为smtp
                        #端口465,protocol设置为smtps
    username: ***@qq.com
    password: ***       #password为授权码,不是qq密码
    properties:
      mail.smtp.socketFactoryClass: javax.net.ssl.SSLSocketFactory
      mail.debug: true

                  

******************

service 层

              

MailService

@Service
public class MailService {

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private TemplateEngine templateEngine;

    public void send(String name, Double salary) throws Exception {
        MimeMessage mimeMessage=javaMailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
        helper.setSubject("入职邮件");
        helper.setFrom("***@qq.com");
        helper.setTo("***@139.com");
        helper.setSentDate(new Date());

        Context context=new Context();
        context.setVariable("name",name);
        context.setVariable("salary",salary);
        String text=templateEngine.process("hiring.html",context);
        helper.setText(text,true);

        javaMailSender.send(helper.getMimeMessage());
    }
}

                      

******************

controller

                  

HelloController

@RestController
public class HelloController {

    @Resource
    private MailService mailService;

    @RequestMapping("/send")
    public String hello(){
        try {
            mailService.send("瓜田李下",20000d);
        }catch (Exception e){
            e.printStackTrace();
        }

        return "success";
    }
}

                      

******************

html 页面

             

hiring.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <img src="/img/lhg.jpeg" alt="联合国" th:width="100">
    <span style="color: orange">欢迎就联合国,你的入职信息如下</span>
    <div>
        <span style="color: blueviolet" th:text="${name}"></span>
        <span style="color: blueviolet" th:text="${salary}"></span>
    </div>
</div>
</body>
</html>

                    

                            

*********************

使用测试

                   

localhost:8080/send控制台输出:

DEBUG: Jakarta Mail version 1.6.7
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle]}
DEBUG: Providers Listed By Protocol: {imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "smtp.qq.com", port 465, isSSL true
220 newxmesmtplogicsvrszc6.qq.com XMail Esmtp QQ Mail Server.
DEBUG SMTP: connected to host "smtp.qq.com", port: 465
EHLO LAPTOP-D73GD8TE
250-newxmesmtplogicsvrszc6.qq.com
250-PIPELINING
250-SIZE 73400320
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2
250-AUTH=LOGIN
250-MAILCOMPRESS
250 8BITMIME
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SIZE", arg "73400320"
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2"
DEBUG SMTP: Found extension "AUTH=LOGIN", arg ""
DEBUG SMTP: Found extension "MAILCOMPRESS", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: protocolConnect login, host=smtp.qq.com, user=2840119419@qq.com, password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM XOAUTH2 
DEBUG SMTP: Using mechanism LOGIN
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN succeeded
DEBUG SMTP: use8bit false
MAIL FROM:<***@qq.com>
250 OK.
RCPT TO:<***@139.com>
250 OK
DEBUG SMTP: Verified Addresses
DEBUG SMTP:   ***@139.com
DATA
354 End data with <CR><LF>.<CR><LF>.
Date: Mon, 9 Aug 2021 23:31:15 +0800 (GMT+08:00)
From: ***@qq.com
To: ***@139.com
Message-ID: <509067576.2.1628523095532@LAPTOP-D73GD8TE>
Subject: =?UTF-8?B?5YWl6IGM6YKu5Lu2?=
MIME-Version: 1.0
Content-Type: multipart/mixed; 
	boundary="----=_Part_0_1100311236.1628523075685"

------=_Part_0_1100311236.1628523075685
Content-Type: multipart/related; 
	boundary="----=_Part_1_1548963931.1628523075695"

------=_Part_1_1548963931.1628523075695
Content-Type: text/html;charset=UTF-8
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE html>
<html lang=3D"en" xmlns=3D"http://www.w3.org/1999/xhtml"
      xmlns:sec=3D"https://www.thymeleaf.org/thymeleaf-extras-springsecurit=
y4">
<head>
    <meta charset=3D"UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <img src=3D"/img/lhg.jpeg" alt=3D"=E8=81=94=E5=90=88=E5=9B=BD" width=3D=
"100">
    <span style=3D"color: orange">=E6=AC=A2=E8=BF=8E=E5=B0=B1=E8=81=94=E5=
=90=88=E5=9B=BD=EF=BC=8C=E4=BD=A0=E7=9A=84=E5=85=A5=E8=81=8C=E4=BF=A1=E6=81=
=AF=E5=A6=82=E4=B8=8B</span>
    <div>
        <span style=3D"color: blueviolet">=E7=93=9C=E7=94=B0=E6=9D=8E=E4=B8=
=8B</span>
        <span style=3D"color: blueviolet">20000.0</span>
    </div>
</div>
</body>
</html>
------=_Part_1_1548963931.1628523075695--

------=_Part_0_1100311236.1628523075685--
.
250 OK: queued as.
DEBUG SMTP: message successfully delivered to mail server
QUIT
221 Bye.

                   

                                   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值