Java實現郵箱發送驗證碼
阿新 • • 發佈:2017-06-20
int res intern 服務 char ati aging err con
第一步,導入JAR包,JAR包下載地址[http://pan.baidu.com/s/1kVRvGyF]
正式代碼:
首先書寫一個工具類:
MailUtil
import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; /** * 郵件工具類 */ public class MailUtil { /** * 發送郵件 * @paramto 給誰發 * @param text 發送內容 */ public static void send_mail(String to,String text) throws MessagingException { //創建連接對象 連接到郵件服務器 Properties properties = new Properties(); //設置發送郵件的基本參數 //發送郵件服務器 properties.put("mail.smtp.host", "smtp.huic188.com");//發送端口 properties.put("mail.smtp.port", "25"); properties.put("mail.smtp.auth", "true"); //設置發送郵件的賬號和密碼 Session session = Session.getInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() {//兩個參數分別是發送郵件的賬戶和密碼 return new PasswordAuthentication("[email protected]","這裏寫你的賬號的密碼"); } }); //創建郵件對象 Message message = new MimeMessage(session); //設置發件人 message.setFrom(new InternetAddress("[email protected]")); //設置收件人 message.setRecipient(Message.RecipientType.TO,new InternetAddress(to)); //設置主題 message.setSubject("這是一份測試郵件"); //設置郵件正文 第二個參數是郵件發送的類型 message.setContent(text,"text/html;charset=UTF-8"); //發送一封郵件 Transport.send(message); } }
測試類:
TEST:
import javax.mail.MessagingException; /** * 測試類 */ public class Test { public static void main(String[] args) { try { MailUtil.send_mail("[email protected]", String.valueOf(Math.random() * 999)); System.out.println("郵件發送成功!"); } catch (MessagingException e) { e.printStackTrace(); } } }
Java實現郵箱發送驗證碼