SpringBoot發(fā)郵件

Springboot 使用 JavaMailSender 發(fā)郵件

發(fā)郵件功能,使用還是很普遍的,比如注冊,找回密碼,留言,推送......................我們來看看springboot 是怎么發(fā)郵件的。

1、添加依賴

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

2、配置郵件信息 application.properties

spring.mail.host=smtp.qq.com
spring.mail.username=1006059906@qq.com           //用戶名
spring.mail.password=xxxxooooo                    //密碼,QQ的授權(quán)碼
//下面是安全認(rèn)證,不加會報(bào)503錯(cuò)誤
spring.mail.properties.mail.smtp.auth=true         
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.default-encoding=UTF-8

這個(gè)如果在windows 一般都沒什么問題,但在第三方運(yùn)營商可能會有一個(gè)問題,就是 25 端口 被禁用。導(dǎo)致郵件發(fā)不了。
解決方案:換端口,具體實(shí)現(xiàn)下面有

3、代碼示例

實(shí)現(xiàn)類如下:

package top.lrshuai.service.impl;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
 
import top.lrshuai.service.MailService;
 
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
 
@Component
public class MailServiceImpl implements MailService{
 
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
 
    @Autowired
    private JavaMailSender mailSender;
 
    @Value("${fromMail}")
    private String from;
 
    /**
     * 發(fā)送文本郵件
     * @param to
     * @param subject
     * @param content
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            logger.info("簡單郵件已經(jīng)發(fā)送。");
        } catch (Exception e) {
            logger.error("發(fā)送簡單郵件時(shí)發(fā)生異常!", e);
        }
 
    }
 
    /**
     * 發(fā)送html郵件
     * @param to
     * @param subject
     * @param content
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
 
        try {
            //true表示需要創(chuàng)建一個(gè)multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
 
            mailSender.send(message);
            logger.info("html郵件發(fā)送成功");
        } catch (MessagingException e) {
            logger.error("發(fā)送html郵件時(shí)發(fā)生異常!", e);
        }
    }
 
 
    /**
     * 發(fā)送帶附件的郵件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath){
        MimeMessage message = mailSender.createMimeMessage();
 
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
 
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            logger.info("帶附件的郵件已經(jīng)發(fā)送。");
        } catch (MessagingException e) {
            logger.error("發(fā)送帶附件的郵件時(shí)發(fā)生異常!", e);
        }
    }
 
 
    /**
     * 發(fā)送正文中有靜態(tài)資源(圖片)的郵件
     * @param to
     * @param subject
     * @param content
     * @param rscPath
     * @param rscId
     */
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
        MimeMessage message = mailSender.createMimeMessage();
 
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            System.out.println("content="+content);
            System.out.println("rscId="+rscId);
            System.out.println("rscPath="+rscPath);
            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);
            mailSender.send(message);
            logger.info("嵌入靜態(tài)資源的郵件已經(jīng)發(fā)送。");
        } catch (MessagingException e) {
            logger.error("發(fā)送嵌入靜態(tài)資源的郵件時(shí)發(fā)生異常!", e);
        }
    }
}

測試類

package top.lrshuai.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import top.lrshuai.service.MailService;

/**
 * 
 * @author tyro
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {

    @Autowired
    private MailService mailService;

    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void testSimpleMail() throws Exception {
        mailService.sendSimpleMail("1071426959@qq.com","test simple mail"," hello this is simple mail");
    }

    @Test
    public void testHtmlMail() throws Exception {
        String content="<html>\n" +
                "<body>\n" +
                "    <h3>hello world ! 這是一封html郵件!</h3>\n" +
                "</body>\n" +
                "</html>";
        mailService.sendHtmlMail("1071426959@qq.com","test simple mail",content);
    }

    @Test
    public void sendAttachmentsMail() {
        String filePath="E:\\lrs\\github\\SSM\\README.txt";
        mailService.sendAttachmentsMail("1071426959@qq.com", "主題:帶附件的郵件", "有附件,請查收!", filePath);
    }


    @Test
    public void sendInlineResourceMail() {
        String rscId ="id001";
        String content="<html><body>這是有圖片的郵件:<img src=\"cid:" + rscId + "\" ></body></html>";
        String imgPath = "E:\\lrs\\pic\\logo.jpg";

        mailService.sendInlineResourceMail("1071426959@qq.com", "主題:這是有圖片的郵件", content, imgPath, rscId);
    }


    @Test
    public void sendTemplateMail() {
        //創(chuàng)建郵件正文
        Context context = new Context();
        context.setVariable("id", "168");
        String emailContent = templateEngine.process("emailTemplate", context);

        mailService.sendHtmlMail("1071426959@qq.com","主題:這是模板郵件",emailContent);
    }
}

可能出現(xiàn)的問題

send mail err:Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.qq.com, 25; timeout -1

在本地windows 是可以發(fā)送成功的
懷疑是端口問題,好吧,我用的是 25 端口,開了之后還是連接超時(shí)。
那么就很有可能是你的服務(wù)器的運(yùn)營商將25端口封禁了!

修改端口為465

spring.mail.host=smtp.qq.com
spring.mail.username=1006059906@qq.com
spring.mail.password=這個(gè)是你的授權(quán)碼
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.default-encoding=UTF-8
spring.mail.port=465
spring.mail.properties.mail.smtp.socketFactory.port = 465
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = false

代碼地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容