欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java+jsp+struts2实现发送邮件功能

程序员文章站 2024-03-03 21:57:34
以下总结是2016/3/23在做一个网站时遇到的一个功能模块,现在将总结从为知笔记上搬家到csdn,与大家共享,欢迎指正。 0.准备工作   0.1先建立...

以下总结是2016/3/23在做一个网站时遇到的一个功能模块,现在将总结从为知笔记上搬家到csdn,与大家共享,欢迎指正。

java+jsp+struts2实现发送邮件功能java+jsp+struts2实现发送邮件功能

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服务,登陆邮箱,点击“设置”进行开启。

java+jsp+struts2实现发送邮件功能

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。