ssm實現qq郵箱傳送驗證碼
阿新 • • 發佈:2021-10-10
ssm實現qq郵箱傳送驗證碼
匯入maven依賴
<!--郵箱驗證碼--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>5.1.10.RELEASE</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency>
新建 mail.properties 進行配置
#伺服器主機名 smtp.xx.com
mail.smtp.host=smtp.qq.com
mail.smtp.username=qq號@qq.com
#客戶端授權碼
mail.smtp.password=授權碼
#編碼字元
mail.smtp.defaultEncoding=utf-8
#是否進行使用者名稱密碼校驗
mail.smtp.auth=true
#設定超時時間
mail.smtp.timeout=20000
在springMVC配置檔案配置
<!--QQ傳送郵箱驗證碼--> <!--讀取屬性檔案--> <context:property-placeholder location="classpath:mail.properties" ignore-unresolvable="true"/> <!--配置郵件介面--> <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="${mail.smtp.host}"/> <property name="username" value="${mail.smtp.username}"/> <property name="password" value="${mail.smtp.password}"/> <property name="defaultEncoding" value="${mail.smtp.defaultEncoding}"/> <property name="javaMailProperties"> <props> <prop key="mail.smtp.auth">${mail.smtp.auth}</prop> <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop> </props> </property> </bean>
controller 進行配置
@Autowired private JavaMailSender javaMailSender;//import org.springframework.mail.javamail.JavaMailSender; @Value("${mail.smtp.username}") private String emailFrom; /*驗證碼傳送*/ @PostMapping("/send") public Result senMsg(HttpSession httpSession, @RequestParam("userEmail") String userEmail) { //生成六位數驗證碼 String Captcha = String.valueOf(new Random().nextInt(899999) + 100000); httpSession.setAttribute("Captcha", Captcha);//儲存驗證碼 SimpleMailMessage message = new SimpleMailMessage(); //發件人的郵箱地址 message.setFrom(emailFrom); //收件人的郵箱地址 message.setTo(userEmail); //郵件主題 message.setSubject("驗證碼"); //郵件內容 message.setText("驗證碼:" + Captcha); //傳送郵件 javaMailSender.send(message); return Result.success(200, "傳送成功", null); }
推薦部落格:https://blog.csdn.net/weixin_42356887/article/details/105638417