本文實例為大家分享了java實現發送郵箱驗證碼的具體代碼,供大家參考,具體內容如下
添加依賴
<!-- 郵箱驗證碼 https://mvnrepository.com/artifact/org.apache.commons/commons-email --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.4</version> </dependency>
以qq郵箱為例登入qq郵箱找到設置
找到 POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務 開啟 :IMAP/SMTP服務 我已經開啟了,不做演示了
驗證碼生成的工具方法
/** * 生成隨機驗證碼 * @param number 幾位數 * @return */ @Override public String generateVerifyCode(int number) { Random random = new Random(); StringBuilder builder = new StringBuilder(); for (int i = 1; i <= number; i++) { builder.append(random.nextInt(10)); } return builder.toString(); }
發送驗證碼
/** * 發送驗證碼 * @param email * @return */ @Override public int sendAuthCodeEmail(String email) { try { HtmlEmail mail = new HtmlEmail(); /*發送郵件的服務器 126郵箱為smtp.126.com,163郵箱為163.smtp.com,QQ為smtp.qq.com*/ mail.setHostName("smtp.qq.com"); /*不設置發送的消息有可能是亂碼*/ mail.setCharset("UTF-8"); /*IMAP/SMTP服務的密碼*/ mail.setAuthentication("發送消息的郵箱如:[email protected]", "密碼"); /*發送郵件的郵箱和發件人*/ mail.setFrom("發件郵箱", "發件人"); /*使用安全鏈接*/ mail.setSSLOnConnect(true); /*接收的郵箱*/ mail.addTo("[email protected]"); /*驗證碼*/ String code = this.generateVerifyCode(6); /*設置郵件的主題*/ mail.setSubject("注冊驗證碼"); /*設置郵件的內容*/ mail.setMsg("尊敬的用戶:你好! 注冊驗證碼為:" + code + "(有效期為一分鐘)"); mail.send();//發送 } catch (Exception e) { return 0; } return 1; }
運行結果
完成
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_43898141/article/details/119886216