Springboot發送QQ郵件, 解決Could not connect to SMTP host: smtp.qq.com, port:XXXX


簡單的說,就是端口不能訪問,阿里雲服務器屏蔽了25端口,用587就可以

上代碼:

 

依賴:

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

配置:
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
spring.mail.username=你的郵箱賬號
spring.mail.password=你的授權碼,注意,是授權碼,不是登錄密碼
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.properties.mail.smtp.port=587

代碼(不想寫接口,隨便用吧,見笑):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author CqLiu
 * @create 2020-11-27 17:01
 */
@Service
public class QQMailService {
    @Autowired
    private JavaMailSender mailSender;

    @Value("${mail.fromMail.addr}")
    private String from;

    public void simple(String to,String title,String txt){
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom(from);//發送者
        msg.setTo(to);//接收者
        msg.setSubject(title);//標題
        msg.setText(txt);//內容
        mailSender.send(msg);
    }

    public void html(String to,String title,String doc){
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);//發送人
            helper.setTo(to);//接收人
            helper.setSubject(title);//標題
            helper.setText(doc, true);//發送的內容
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM