您好,登錄后才能下訂單哦!
以下總結是2016/3/23在做一個網站時遇到的一個功能模塊,現在將總結從為知筆記上搬家到CSDN,與大家共享,歡迎指正。
0.準備工作
0.1先建立一個web項目,添加struts2開發包
0.2.需要另外導入一下兩個jar包 mail.jar,activation.jar,可以自己網上下載,很多的!
以下為詳細過程!
1.index.jsp頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <head> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <s:form action="sendTextMail" namespace="/mail"> <s:textfield name="to" label="收件人郵箱:"></s:textfield> <s:textfield name="subject" label="主題"></s:textfield> <s:textarea name="content" label="內容" rows="5"></s:textarea> <s:submit value="發送"></s:submit> </s:form> </body> </html>
2.SendTestAction.java類
package com.phone.action; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import com.opensymphony.xwork2.ActionSupport; import com.phone.util.MailSenderInfo; import com.phone.util.SimpleMailSender; public class SendTestAction extends ActionSupport { private static final long serialVersionUID = 1L; private String to; private String qq; private String password; private String subject; private String content; public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String execute() throws Exception { MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setMailServerHost("smtp.163.com"); mailInfo.setMailServerPort("25"); mailInfo.setValidate(true); mailInfo.setFromAddress("m15504506083@163.com");//自己郵箱 mailInfo.setToAddress(to);//目標郵箱 mailInfo.setUserName("m15504506083@163.com");//自己郵箱 //需要開啟此郵箱的POP3/SMTP/IMAP服務,具體設置進入郵箱以后在“設置”里進行開啟 mailInfo.setPassword("syfhhd52");//自己郵箱密碼 //System.out.println("password="+password); mailInfo.setSubject(subject); mailInfo.setContent(content); boolean isSend = SimpleMailSender.sendTextMail(mailInfo); /*HttpServletResponse response; PrintWriter out = response.getWriter();*/ if(isSend){ return SUCCESS; //return out.write("<script>alert('發送成功!');history.back();</script>"); } addActionError("發送失敗!"); return INPUT; } }
3.3個主要實現發送郵件的類
3.1 MailSenderInfo.java –郵件實體類
package com.phone.util; import java.util.Properties; public class MailSenderInfo { //發送郵件服務器IP private String mailServerHost ; //發送郵件服務器端口 private String mailServerPort = "25"; //郵件發送地址 private String fromAddress; //郵件接受者地址 private String toAddress; //發送郵件服務器的登錄用戶名 private String userName; //發送郵件服務器的登錄密碼 private String password; //是否需要身份驗證 private boolean validate = false; //郵件主題 private String subject; //郵件的文本內容 private String content; //郵件附件的文件名 private String[] attachFileNames; //發送人的郵件信息,在創建Session是使用 public Properties getProperties(){ Properties p = new Properties(); p.put("mail.smtp.host", this.mailServerHost); p.put("mail.smtp.port", this.mailServerPort); p.put("mail.smtp.auth", validate ? "true" : "false"); return p; } public String getMailServerHost() { return mailServerHost; } public void setMailServerHost(String mailServerHost) { this.mailServerHost = mailServerHost; } public String getMailServerPort() { return mailServerPort; } public void setMailServerPort(String mailServerPort) { this.mailServerPort = mailServerPort; } public String getFromAddress() { return fromAddress; } public void setFromAddress(String fromAddress) { this.fromAddress = fromAddress; } public String getToAddress() { return toAddress; } public void setToAddress(String toAddress) { this.toAddress = toAddress; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isValidate() { return validate; } public void setValidate(boolean validate) { this.validate = validate; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String[] getAttachFileNames() { return attachFileNames; } public void setAttachFileNames(String[] attachFileNames) { this.attachFileNames = attachFileNames; } }
3.2 MyAuthenticator.java —認證所需
package com.phone.util; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class MyAuthenticator extends Authenticator{ private String userName; private String password; public MyAuthenticator() {} public MyAuthenticator(String userName, String password) { this.userName = userName; this.password = password; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }
3.3 SimpleMailSender.java –構建發送郵件
package com.phone.util; import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class SimpleMailSender { // 發送文本格式的郵件 public static boolean sendTextMail(MailSenderInfo mailInfo) { MyAuthenticator authenticator = null; Properties properties = mailInfo.getProperties(); // 如果需要身份認證,則創建一個密碼驗證器 if (mailInfo.isValidate()) { authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根據發件人的服務器信息和發件人用戶名和密碼構造一個發送郵件的session Session sendMailSession = Session.getDefaultInstance(properties, authenticator); try { // 根據session創建一個郵件消息 Message mailMessage = new MimeMessage(sendMailSession); // 創建郵件發送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 設置郵件消息的發送者 mailMessage.setFrom(from); // 創建郵件的接收者地址,并設置到郵件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); mailMessage.setRecipient(Message.RecipientType.TO, to); // 設置郵件消息的主題 mailMessage.setSubject(mailInfo.getSubject()); // 設置郵件消息發送的時間 mailMessage.setSentDate(new Date()); // 設置郵件消息的主要內容 String mailContent = mailInfo.getContent(); mailMessage.setText(mailContent); // 發送郵件 Transport.send(mailMessage); return true; } catch (Exception e) { e.printStackTrace(); } return false; } // 發送HTML格式的郵件 public static boolean sendHtmlMail(MailSenderInfo mailInfo) { // 判斷是否需要身份認證 MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); // 如果需要身份認證,則創建一個密碼驗證器 if (mailInfo.isValidate()) { authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session Session sendMailSession = Session.getInstance(pro, authenticator); try { // 根據session創建一個郵件消息 Message mailMessage = new MimeMessage(sendMailSession); // 創建郵件發送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 設置郵件消息的發送者 mailMessage.setFrom(from); // 創建郵件的接收者地址,并設置到郵件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); // Message.RecipientType.TO屬性表示接收者的類型為TO mailMessage.setRecipient(Message.RecipientType.TO, to); // 設置郵件消息的主題 mailMessage.setSubject(mailInfo.getSubject()); // 設置郵件消息發送的時間 mailMessage.setSentDate(new Date()); // MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象 Multipart mainPart = new MimeMultipart(); // 創建一個包含HTML內容的MimeBodyPart BodyPart html = new MimeBodyPart(); // 設置HTML內容 html.setContent(mailInfo.getContent(), "text/html;charset=utf-8"); mainPart.addBodyPart(html); // 將MiniMultipart對象設置為郵件內容 mailMessage.setContent(mainPart); // 發送郵件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } }
4. struts.xml配置
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <!-- 設置瀏覽器不緩存 --> <constant name="struts.serve.static.browserCache" value="false"></constant> <!-- 修改XML后不重啟自動加載 --> <constant name="struts.configuration.xml.reload" value="true"></constant> <!-- 打印更詳細的錯誤信息 --> <constant name="struts.devMode" value="true"></constant> <package name="mail" namespace="/mail" extends="struts-default"> <action name="sendTextMail" class="com.phone.action.SendTestAction"> <result name="success">/success.jsp</result> <result name="input">/index.jsp</result> </action> </package> </struts>
注意:
登陸所用郵箱必須開啟POP3/SMTP/IMAP服務,登陸郵箱,點擊“設置”進行開啟。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。