Springboot傳送QQ郵件, 解決Could not connect to SMTP host: smtp.qq.com, port:XXXX
阿新 • • 發佈:2020-11-27
簡單的說,就是埠不能訪問,阿里雲伺服器遮蔽了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(); } } }