1. 程式人生 > >email工具類使用及設置

email工具類使用及設置

tst image 網站 str nbsp sta name dto rom

日常生活中,經常遇到這種情況,在註冊新賬號時,網站會要求輸入郵箱,並且註冊成功後會發一封郵件到你的郵箱,點擊郵件中的鏈接後賬號才能夠激活並使用,

網站商家有這兩個目的,一是辨別惡意操作,二是定向推廣,有了你郵箱就方便給你發廣告。下面介紹一種開發中常用的郵箱驗證工具類

①完整郵箱發送代碼:

 1 package com.didinx.filter;
 2 
 3 import org.apache.commons.mail.EmailException;
 4 import org.apache.commons.mail.HtmlEmail;
 5 import org.junit.jupiter.api.Test;
6 7 /** 8 * @author o_0sky 9 * @date 2019/2/12 13:35 10 */ 11 public class emailtsk { 12 @Test 13 public void testMail() throws EmailException { 14 //創建HtmlEmail對象,封裝郵件發送參數 15 HtmlEmail htmlEmail = new HtmlEmail(); 16 //設置郵件服務器地址 17 htmlEmail.setHostName("smtp.163.com
"); 18 //設置你的郵箱賬號和第三方使用郵件授權碼 19 htmlEmail.setAuthentication("xxx@163.com", "lin123"); 20 //設置收件人,多個收件人的話,此語句多寫幾次 21 htmlEmail.addTo("xxx@163.com","新註冊用戶"); 22 //htmlEmail.addTo("[email protected]","test"); 23 //設置發件信息 24 htmlEmail.setFrom("xxx@163.com","【博客園】
"); 25 //設置郵件編碼 (網易郵箱解碼為gb2312) 26 htmlEmail.setCharset("gb2312"); 27 //設置郵件主題 28 htmlEmail.setSubject("【博客園註冊激活郵件】"); 29 //設置郵件正文 30 htmlEmail.setMsg("<h2>恭喜你,註冊成功!</h2>"+ 31 "<a href=‘http://localhost:8080/userServlet?methodName=active&code=123‘>請點擊鏈接進行激活</a>"); 32 //發送郵件 33 htmlEmail.send(); 34 } 35 36 }
②封裝成工具類:
《1》掛載配置文件:
技術分享圖片

《2》抽取工具類



 1 package com.heima.travel.utils;
 2 
 3 import org.apache.commons.mail.EmailException;
 4 import org.apache.commons.mail.HtmlEmail;
 5 
 6 import java.util.ResourceBundle;
 7 
 8 /**
 9  * @author buguniao
10  * @version v1.0
11  * @date 2019/1/18 17:00
12  * @description 郵件發送相關的工具類
13  **/
14 public class MailUtil {
15 
16     private static String hostname;
17     private static String username;
18     private static String password;
19     private static String charset;
20 
21 
22     //提前加載郵件發送相關的配置信息
23     static {
24         ResourceBundle bundle = ResourceBundle.getBundle("mail");
25         hostname = bundle.getString("hostname");
26         username = bundle.getString("username");
27         password = bundle.getString("password");
28         charset = bundle.getString("charset");
29     }
30 
31 
32     /**
33      * 發送郵件
34      * @param emailTo
35      * @param msg
36      */
37     public static void emeilSend(String emailTo,String msg) throws EmailException {
38 
39         HtmlEmail htmlEmail = new HtmlEmail();
40 
41         //服務器參數
42         htmlEmail.setHostName(hostname);
43         htmlEmail.setAuthentication(username, password);
44         htmlEmail.setCharset(charset);
45 
46         //發件人和收件人
47         htmlEmail.setFrom(username, "【博客園官網】");
48         htmlEmail.addTo(emailTo, "新註冊用戶");
49 
50         //郵件內容
51         htmlEmail.setSubject("【博客園註冊激活郵件】");
52         htmlEmail.setMsg(msg);
53 
54         //發送郵件
55         htmlEmail.send();
56     }
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 }



email工具類使用及設置