专业的JAVA编程教程与资源

网站首页 > java教程 正文

使用spring boot 发送邮件(springboot发送outlook邮件)

temp10 2024-09-14 12:49:59 java教程 13 ℃ 0 评论

SMTP 简介#

SMTP服务器使用端口25,处于安全考虑现在很多服务器使用SSL,TLS加密,此时使用额外的端口来做加密处理,SSL对应的是465端口, TLS对应的是587端口。 例如:

smtp.gmail.com
Port 465 (SSL required)
Port 587 (TLS required)
Dynamic IPs allowed

使用openssl 测试 SMTP 服务器#

  • Step 1: 建立 starttls 连接
openssl s_client -connect smtp.mail.yahoo.com:587 -starttls smtp
CONNECTED(00000003)
depth=1 C = US, O = DigiCert Inc, OU = www.digicert.com, CN = DigiCert SHA2 High Assurance Server CA
verify error:num=20:unable to get local issuer certificate
---
Certificate chain
 0 s:/C=US/ST=California/L=Sunnyvale/O=Yahoo Holdings, Inc./CN=smtp.mail.yahoo.com
   i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 High Assurance Server CA
 1 s:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 High Assurance Server CA
   i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance EV Root CA
---
Server certificate
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
subject=/C=US/ST=California/L=Sunnyvale/O=Yahoo Holdings, Inc./CN=smtp.mail.yahoo.com
issuer=/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 High Assurance Server CA
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: ECDH, B-571, 570 bits
---
SSL handshake has read 4139 bytes and written 603 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384
    Session-ID: 5C38217626A530D017658EA1137482BA2D3DAC724D09EE712AEEF570085CD13D
    Session-ID-ctx:
    Master-Key: FB777B06585B4B1A075DCC2EAFF1E831548E4D00BE764C9CD2C6743E99E6C9E1FDFAE37EAA65226D7D2E7784380757CA
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1547182454
    Timeout   : 300 (sec)
    Verify return code: 20 (unable to get local issuer certificate)
---
250 STARTTLS
  • Step 2: 测试连接
  • EHLO localhost 或者 HELO localhost

    返回结果: 这里返回的是目标服务器支持的登录方法,可以看到最后一行显示服务器支持四种登录方式 分别是 PLAIN, LOGIN, XOAUTH2,OAUTHBEARER, 我们下面使用第二种

    使用spring boot 发送邮件(springboot发送outlook邮件)

    • AUTH LOGIN
    250-smtp412.mail.sg3.yahoo.com Hello localhost [113.201.50.30])
    250-PIPELINING
    250-ENHANCEDSTATUSCODES
    250-8BITMIME
    250-SIZE 41697280
    250 AUTH PLAIN LOGIN XOAUTH2 OAUTHBEARER
    • Step 3: 登录
    AUTH LOGIN
    334 VXNlcm5hbWU6    # 返回结果,等待输入用户名
                        # 通过base64加密用户名, 可以通过python base64,
                        # 进行加密base64.b64encode('example@gmail.com')
    ZGV2Lm5nb3JnYW5pem
    
    334 UGFzc3dvcmQ6    # 返回结果, 等待输入密码
    amV0LnFpbkBwdWxzZX  # 此为密码,密码同样需要base64加密

    返回结果: 如果用户名密码正确会显示235 2.7.0 Accepted 否则会显示 535 Authentication failed

    235 2.7.0 Accepted
    535 5.7.1 Authentication failed

    通过spring boot mail 实现邮件发送功能#

    当你通过openssl 验证SMTP服务器能正常登录时,此时就可以通过编码来实现邮件发送功能,有时候不同的smtp服务器需要不同的配置 很多时候SMTP服务器为了安全会封锁外部访问,导致无法发送邮件。

    SMTP 属性配置, 修改application.properties

    # Yahoo 邮件服务器
    spring.mail.host=smtp.mail.yahoo.com
    spring.mail.port=587
    
    # Gmail 邮件服务器
    spring.mail.host=smtp.gmail.com
    spring.mail.port=587
    
    # Outlook 邮件服务器
    spring.mail.host=smtp-mail.outlook.com
    spring.mail.port=587
    
    spring.mail.username=xxxxx@outlook.com
    spring.mail.password=xxxxx
    
    spring.mail.properties.mail.smtp.connectiontimeout=5000   #连接超时时间
    spring.mail.properties.mail.smtp.timeout=3000
    spring.mail.properties.mail.smtp.writetimeout=5000
    
    spring.mail.properties.mail.debug=true
    spring.mail.properties.mail.smtp.starttls.enable=true
    spring.mail.properties.mail.smtp.starttls.required=true

    核心代码 EmailService:

    spring-boot-starter-mail 已经封装了一些方法,我们这里可以直接使用JavaMailSender来发送邮件,首先,我们需要构造一个MimeMessage, 然后使用MimeMessageHelper对message进行赋值,包括收件人,发件人,主题以及邮件内容,我们可以构造使用一个Freemaker,构造一个邮件模版,关键信息我们可以通过占位符显示,通过哈希表在构造的时候传入

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.core.env.Environment;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.MimeMessageHelper;
    import org.springframework.stereotype.Service;
    
    import javax.mail.internet.MimeMessage;
    import java.util.Map;
    
    import freemarker.template.Configuration;
    import freemarker.template.Template;
    import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
    
    @Service
    public class EmailService
    {
        @Autowired
        Environment env;
    
        @Autowired
        private JavaMailSender sender;
    
        @Autowired
        private Configuration freemarkerConfig;
    
    
        public void sendResetEmail(String to, Map<String,Object> params) throws Exception{
            MimeMessage message = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/");
            Template t = freemarkerConfig.getTemplate("emails/Example.ftl");             //设置邮件模版
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(t, params);  //将邮件模版转换成邮件正文
            helper.setTo(to);
            helper.setFrom(env.getProperty("spring.mail.username"));
            helper.setText(text,true);
            helper.setSubject("Reset Password Email");
            sender.send(message);
        }
    
    }

    Example.ftl: 邮件模版, 可以在邮件模版里定义变量,构造邮件内容的时候通过哈希表传入

    <html>
      <body>
      <h3>Hi ${user}: </h3>
      <h3>welcome to the application!</h3>
      </body>
    </html>

    Tags:

    本文暂时没有评论,来添加一个吧(●'◡'●)

    欢迎 发表评论:

    最近发表
    标签列表