springboot實現發送QQ郵箱
springboot發送電子郵箱,供大家參考,具體內容如下
1.開啟qq郵箱開啟IMAP/SMTP服務*
首先進入qq郵箱
點擊設置
點擊賬戶,然后往下拉
開啟IMAP/SMTP服務
開啟成功得到授權密碼,這個要記住,一會用
2.引入pom依賴
<!--發送郵箱--><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> <version>2.2.5.RELEASE</version></dependency>
3.配置application.properties
# QQ郵箱配置spring.mail.host=smtp.qq.com#發件人QQ郵箱地址spring.mail.username=發件人的qq郵箱#QQ郵箱授權碼spring.mail.password=得到的授權密碼#以下三項不用改動spring.mail.properties.mail.smtp.auth=truespring.mail.properties.mail.smtp.starttls.enable=truespring.mail.properties.mail.smtp.starttls.required=true
4.創建發送電子郵箱controller
我這里收件人地址寫死了,當然可以作為參數,訪問這個方法的時候把參數加上就行了,效果都是一樣的
package com.wyh.controller;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.web.bind.annotation.*;import javax.annotation.Resource;import javax.mail.Address;import javax.mail.MessagingException;import java.util.ArrayList;@RestControllerpublic class EmailController { @Resource private JavaMailSender javaMailSender; //這一步是獲取application.properties中設置的發件人郵箱地址 @Value('${spring.mail.username}') private String username; /** /* @Author 魏一鶴 * @Description 發送郵箱 * @Date 0:09 2021/5/19 * @Param [] * @return void **/ @RequestMapping('/sendEmail') public String sendMail() { //String address//發郵件 SimpleMailMessage message = new SimpleMailMessage(); //發件人郵件地址(上面獲取到的,也可以直接填寫,string類型) message.setFrom(username); //要發送的qq郵箱(收件人地址) message.setTo('1581622479@qq.com');//address //郵件主題 message.setSubject('java調用QQ郵箱發送'); //郵件正文 message.setText('我是用java發送的QQ郵箱');//!!! javaMailSender.send(message); return '發送成功!'; }}
5.查看效果
在我的qq郵箱就能看到我們發送的內容了
然后換一種寫法,把收件人的地址作為參數
package com.wyh.controller;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.web.bind.annotation.*;import javax.annotation.Resource;import javax.mail.Address;import javax.mail.MessagingException;import java.util.ArrayList;@RestControllerpublic class EmailController { @Resource private JavaMailSender javaMailSender; //這一步是獲取application.properties中設置的發件人郵箱地址 @Value('${spring.mail.username}') private String username; /** /* @Author 魏一鶴 * @Description 發送郵箱 * @Date 0:09 2021/5/19 * @Param [] * @return void **/ @RequestMapping('/sendEmail') public String sendMail(String address) { //String address//發郵件 SimpleMailMessage message = new SimpleMailMessage(); //發件人郵件地址(上面獲取到的,也可以直接填寫,string類型) message.setFrom(username); //要發送的qq郵箱(收件人地址) message.setTo(address);//address //郵件主題 message.setSubject('java調用QQ郵箱發送'); //郵件正文 message.setText('我是用java發送的QQ郵箱');//!!! javaMailSender.send(message); return '發送成功!'; }}
效果都是一樣的。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: