《JavaWeb从入门到改行》注册时向指定邮箱发送邮件激活
javaMail API
?javaMail是SUN公司提供的針對郵件的API 。 兩個jar包 ?mail.jar 和 activation.jar
java mail中主要類:javax.mail.Session、javax.mail.internet.MimeMessage、javax.mail.Transport。
| ? ?Session ? ? ? ? ?? | 表示會話,即客戶端與郵件服務器之間的會話!想獲得會話需要給出賬戶和密碼,當然還要給出服務器名稱。在郵件服務中的Session對象,就相當于連接數(shù)據(jù)庫時的Connection對象。 |
| MimeMessage | 表示郵件類,它是Message的子類。它包含郵件的主題(標題)、內容,收件人地址、發(fā)件人地址,還可以設置抄送和暗送,甚至還可以設置附件。 |
| Transport | 用來發(fā)送郵件。它是發(fā)送器! |
?
?
?
第一步:獲得Session
第二步:創(chuàng)建MimeMessage對象
第三步:發(fā)送郵件
javaMail 代碼分析
?代碼在web項目中沒有任何問題,但是在java中用@Test做測試時會報錯,
到下面路徑中找到javaee.jar文件,把javax.mail刪除!!!
D:\Program Files\MyEclipse\Common\plugins\com.genuitec.eclipse.j2eedt.core_10.0.0.me201110301321\data\libraryset\EE_5 ??
需要注意: ?如果出現(xiàn)如下報錯信息:
javax.mail.AuthenticationFailedException: failed to connect
?基本上密碼有問題,這個密碼并不是郵箱帳號的私人密碼,而是授權密碼。 關于郵箱授權密碼請自行百度。
/*** 文本郵件* @throws MessagingException* @throws javax.mail.MessagingException*/@Testpublic void fun() throws MessagingException, javax.mail.MessagingException{/** 1. 得到Session* 導包: java.util.properties;import javax.mail.Authenticator;import javax.mail.Session;*/Properties props = new Properties();props.setProperty("mail.host", "smtp.163.com");//設置服務器主機名props.setProperty("mail.smtp.auth", "true"); //設置需要認證//Authenticator是一個接口表示認證器,即校驗客戶端的身份。我們需要自己來實現(xiàn)這個接口,實現(xiàn)這個接口需要使用賬戶和密碼。Authenticator auth = new Authenticator(){ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("zhaoyuqiang2017","z123456"); //用戶名和密碼 }};Session session = Session.getInstance(props,auth);/** 2. 創(chuàng)建MimeMessage* import javax.mail.internet.MimeMessage;* RecipientType.TO正常* RecipientType.CC抄送* RecipientType.BCC暗送*/MimeMessage msg = new MimeMessage(session);msg.setFrom(new InternetAddress("zhaoyuqiang2017@163.com"));//設置發(fā)件人msg.setRecipients(RecipientType.TO, "425680992@qq.com");//設置收件人msg.setSubject("這是標題");//郵件標題msg.setContent("我愛你!","text/html;charset=utf-8");//設置郵件內容/** 3.發(fā)郵件*/Transport.send(msg);}?
/*** 附件郵件* @throws AddressException* @throws MessagingException* @throws IOException */@Testpublic void fun1() throws AddressException, MessagingException, IOException{Properties props = new Properties();props.setProperty("mail.host", "smtp.163.com");props.setProperty("mail.smtp.auth", "true");Authenticator auth = new Authenticator(){@Overrideprotected PasswordAuthentication getPasswordAuthentication() {// TODO Auto-generated method stubreturn new PasswordAuthentication("zhaoyuqiang2017","z123456");}};Session session = Session.getInstance(props,auth);MimeMessage msg = new MimeMessage(session);msg.setFrom(new InternetAddress("zhaoyuqiang2017@163.com"));//設置發(fā)件人msg.setRecipients(RecipientType.TO, "425680992@qq.com");//設置收件人msg.setSubject("這是標題-有附件");//郵件標題/*** 有附件的內容* 郵件體為多部件形式* *//** 1. 創(chuàng)建一個多部件的部件 MimeMultipart* MimeMultipart就是一個集合,裝載多個主體部件* 2. 創(chuàng)建兩個主體部件MimeBodyPart,一個是文本part1* 3. 設置主體部件的內容* 4. 把主體部件加到list集合中* 5. 創(chuàng)建兩個主體部件MimeBodyPart,一個是附件part2* 6. 設置附件的內容* 7. 設置顯示的文件名稱* 8. 把主體部件加到list集合中* 3. 把MimeMultipart設置給MimeMessage的內容 */MimeMultipart list = new MimeMultipart();MimeBodyPart part1 = new MimeBodyPart();part1.setContent("我愛你,","text/html;charset=utf-8");list.addBodyPart(part1);MimeBodyPart part2 = new MimeBodyPart();part2.attachFile(new File("D:/吉澤明步.jpg"));part2.setFileName(MimeUtility.encodeText("大美女.jpg"));//encodeText解決亂碼 list.addBodyPart(part2);msg.setContent(list);Transport.send(msg);}為了簡化代碼,在實際操作中往往需要把重復代碼進行封裝,需要導入itcast-tools.jar(下載:https://files.cnblogs.com/files/zyuqiang/itcast-tool.rar ) ?,在本文附加的項目中,會把郵件相關的參數(shù)信息都放在配置文件中。?
/*** 文本郵件* 用小工具來簡化郵件* @throws MessagingException* @throws IOException*/@Testpublic void fun() throws MessagingException, IOException{/** 1. 得到Session*/Session session = MailUtils.createSession("smtp.163.com","zhaoyuqiang2017","z123456");/** 2. 創(chuàng)建郵件對象*/Mail mail = new Mail("zhaoyuqiang2017@163.com","425680992@qq.com","這個是標題-工具", "用工具愛你");/*** 添加附件* 2個附件*/AttachBean ab1 = new AttachBean(new File("D:/吉澤明步.jpg"), "美女.jpg");AttachBean ab2 = new AttachBean(new File("D:/吉澤明步.jpg"), "小美女.jpg");mail.addAttach(ab1);mail.addAttach(ab2);/** 3. 發(fā)送*/MailUtils.send(session, mail); }?
?
項目案例_用戶注冊時發(fā)送郵件到指定郵箱,并且激活。
?說明: ?用戶注冊,填入指定郵箱,系統(tǒng)會自動發(fā)送到指定郵箱一個超鏈接,讓用戶去指定郵箱點擊一個超鏈接激活,激活后才可以正常登陸。
? ? ? ? ? ? 本項目把郵件相關的參數(shù)信息都放在配置文件中。?
1 CREATE TABLE tb_user( 2 uid CHAR(32) PRIMARY KEY,/*主鍵*/ 3 email VARCHAR(50) NOT NULL,/*郵箱*/ 4 `code` CHAR(64) NOT NULL,/*激活碼*/ 5 state BOOLEAN/*用戶狀態(tài),有兩種是否激活*/ 6 ); 數(shù)據(jù)庫?只給出核心源碼,全部項目(包括c3p0文件、郵件文件等)請下載該項目查看, 項目的運行,注意需要修改c3p0配置文件中數(shù)據(jù)庫名稱
1 package cn.kmust.mail.web.servlet; 2 3 4 import java.io.IOException; 5 import java.text.MessageFormat; 6 import java.util.Properties; 7 8 9 import javax.mail.MessagingException; 10 import javax.mail.Session; 11 import javax.servlet.ServletException; 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet.http.HttpServletResponse; 14 15 import cn.itcast.commons.CommonUtils; 16 import cn.itcast.mail.Mail; 17 import cn.itcast.mail.MailUtils; 18 import cn.itcast.servlet.BaseServlet; 19 import cn.kmust.mail.domin.User; 20 import cn.kmust.mail.exception.UserException; 21 import cn.kmust.mail.service.UserService; 22 23 public class UserServlet extends BaseServlet { 24 private UserService userService = new UserService(); 25 /** 26 * 注冊 27 * 郵件發(fā)送到指定郵箱 28 * @param request 29 * @param response 30 * @return 31 * @throws ServletException 32 * @throws IOException 33 */ 34 public String regist(HttpServletRequest request, HttpServletResponse response) 35 throws ServletException, IOException { 36 37 User form = CommonUtils.toBean(request.getParameterMap(), User.class); 38 /* 39 * 補齊code 40 */ 41 form.setCode(CommonUtils.uuid()+CommonUtils.uuid()); 42 /* 43 * 調用service的注冊功能 44 */ 45 userService.regist(form); 46 /* 47 * 發(fā)送郵件,(包含"缺少收不到重發(fā)"功能) 48 * 準備配置文件email_template.properties 49 * 發(fā)送的郵件方信息放在配置文件中 50 * 發(fā)送內容為一個超鏈接,超鏈接到該類的active方法 51 * <a href ="http://localhost:8080/項目名字/UserServlet?method=active&code={0}">點擊這里完成激活 </a> 52 * 獲取配置文件的內容 53 * 加載配置文件到props中 54 * 獲取主機、發(fā)送用戶、授權密碼、發(fā)送郵件、發(fā)件人、發(fā)件主題、發(fā)送內容 55 * 得到Session 56 * 創(chuàng)建郵件對象 57 * 發(fā)郵件 58 */ 59 Properties props = new Properties(); 60 props.load(this.getClass().getClassLoader(). 61 getResourceAsStream("email_template.properties")); 62 String host = props.getProperty("host"); 63 String uname = props.getProperty("uname"); 64 String pwd = props.getProperty("pwd"); 65 String from = props.getProperty("from"); 66 String to = form.getEmail(); 67 String subject = props.getProperty("subject"); 68 String content = props.getProperty("content"); 69 content = MessageFormat.format(content, form.getCode());//替換{0}占位符 70 71 Session session = MailUtils.createSession(host, uname, pwd); 72 Mail mail = new Mail(from,to,subject,content); 73 try { 74 MailUtils.send(session, mail); 75 } catch (MessagingException e) { 76 } 77 /* 78 * 保存成功信息到msg.jsp 79 */ 80 request.setAttribute("msg", "恭喜您,注冊成功!請馬上到郵箱激活!"); 81 return "f:/msg.jsp"; 82 } 83 /** 84 * 激活功能 85 * @功能 當用戶點擊郵件中的完成激活連接時,訪問這個方法 86 * 調用service的激活方法修改用戶狀態(tài) 87 * @param request 88 * @param response 89 * @return 90 * @throws ServletException 91 * @throws IOException 92 * @throws 93 */ 94 public String active(HttpServletRequest request, HttpServletResponse response) 95 throws ServletException, IOException { 96 /* 97 * 1. 獲取參數(shù)激活碼 98 * 2. 調用service方法完成激活 99 * 如果出現(xiàn)異常,保存異常信息到request域中,轉發(fā)到msg.jsp 100 * 3. 成功,保存成功信息到request域,轉發(fā)msg.jsp 101 */ 102 String code = request.getParameter("code"); 103 try { 104 userService.active(code); 105 request.setAttribute("msg", "恭喜,您激活成功!請登陸"); 106 } catch (UserException e) { 107 request.setAttribute("msg", e.getMessage()); 108 } 109 return "f:/msg.jsp" ; 110 } 111 112 } UserServlet 1 package cn.kmust.mail.service; 2 3 import cn.kmust.mail.dao.UserDao; 4 import cn.kmust.mail.domin.User; 5 import cn.kmust.mail.exception.UserException; 6 7 public class UserService { 8 private UserDao userDao = new UserDao(); 9 /** 10 * 激活功能 11 * @param code 12 * @throws UserException 13 */ 14 public void active(String code) throws UserException { 15 /* 16 * 1. 按激活碼查詢用戶 17 * 2. user不存在,激活碼錯誤 18 * 3. 校驗用戶狀態(tài),如果已激活,說明二次激活,拋出異常 19 * 4. 第一次激活,則修改用戶狀態(tài)為true,表明已經激活 20 */ 21 User user = userDao.findByCode(code); 22 System.out.println("激活狀態(tài)測試:"+user.isState()); 23 if(user == null ) 24 throw new UserException("激活碼無效!"); 25 if(user.isState()) 26 throw new UserException("您已經激活過了!"); 27 userDao.updataState(user.getUid(),true); 28 29 } 30 /** 31 * 注冊功能 32 * @param form 33 */ 34 public void regist(User form) { 35 userDao.add(form); 36 } 37 } UserService 1 package cn.kmust.mail.dao; 2 3 import java.sql.SQLException; 4 import org.apache.commons.dbutils.QueryRunner; 5 import org.apache.commons.dbutils.handlers.BeanHandler; 6 7 import cn.itcast.jdbc.TxQueryRunner; 8 import cn.kmust.mail.domin.User; 9 10 public class UserDao { 11 private QueryRunner qr = new TxQueryRunner(); 12 /** 13 * 通過激活碼查詢用戶 14 * @param code 15 * @return 16 */ 17 public User findByCode(String code) { 18 try{ 19 String sql = "select * from tb_user where code=?" ; 20 return qr.query(sql, new BeanHandler<User>(User.class),code); 21 }catch(SQLException e){ 22 throw new RuntimeException(e); 23 } 24 } 25 /** 26 * 添加用戶 27 * @param form 28 */ 29 public void add(User user) { 30 try{ 31 String sql = "insert into tb_user value(?,?,?,?)"; 32 Object[] params ={user.getUid(),user.getEmail(),user.getCode(),user.isState()}; 33 qr.update(sql,params); 34 }catch(SQLException e){ 35 throw new RuntimeException(e); 36 } 37 38 } 39 /** 40 * 成功激活后修改狀態(tài)為已激活 41 * @param uid 42 * @param b 43 */ 44 public void updataState(String uid, boolean state) { 45 try{ 46 String sql = "update tb_user set state=? where uid=?"; 47 qr.update(sql,state,uid); 48 }catch(SQLException e){ 49 throw new RuntimeException(e); 50 } 51 52 } 53 54 } UserDao?
項目下載:?https://files.cnblogs.com/files/zyuqiang/webMail.rar
?
轉載于:https://www.cnblogs.com/zyuqiang/p/7475363.html
總結
以上是生活随笔為你收集整理的《JavaWeb从入门到改行》注册时向指定邮箱发送邮件激活的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: create_metrology_mod
- 下一篇: 《疯狂Java讲义》(第5版) 李刚