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

使用Java发送带附件的附件的示例

程序员文章站 2024-03-08 09:40:58
这里使用的是javamail技术,前台使用了fckeditor做邮件美化,由于只是示例,后台发送时只是将邮件保存在本地,但是可以查看,如果需要实际发送,请参考我的其他博客文...

这里使用的是javamail技术,前台使用了fckeditor做邮件美化,由于只是示例,后台发送时只是将邮件保存在本地,但是可以查看,如果需要实际发送,请参考我的其他博客文章,我写了很多关于邮件发送的示例!

使用Java发送带附件的附件的示例

jsp页面页面除了引用fckeditor外,要注意我们是需要发送附件的:

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<% 
string path = request.getcontextpath(); 
string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/"; 
%> 
<!doctype html public "-//w3c//dtd html 4.01 transitional//en"> 
<html> 
 <head> 
  <base href="<%=basepath%>"> 
  <title>发送邮件</title> 
  <meta http-equiv="pragma" content="no-cache"> 
  <meta http-equiv="cache-control" content="no-cache"> 
  <meta http-equiv="expires" content="0">   
  <script type="text/javascript" src="fckeditor/fckeditor.js"></script> 
  <script type="text/javascript"> 
  window.onload=function(){ 
    var ofckeditor = new fckeditor( 'content' ) ; 
    //编译器基本路径 
    ofckeditor.basepath = "/pro_04/fckeditor/"; 
    //高度 
    ofckeditor.width=800; 
    //宽度 
    ofckeditor.height=300; 
    //工具条集合名称(default,basic或自己制定,关于fck的使用,博客内有专门文章) 
    //具体的配置可以将默认显示出来然后到fck目录里的fckconfig.js里 
    //fckconfig.toolbarsets["default"]数组中去除不要的功能一共63个功能属性 
    //ofckeditor.toolbarset="basic"; 
    ofckeditor.replacetextarea() ;      
  } 
  </script> 
 </head> 
 <body> 
  <!-- 注意表单格式,这里需要上传附件 --> 
  <form action="sendmailservlet" method="post" enctype="multipart/form-data"> 
  <table> 
    <tr> 
      <td>收件人:</td> 
       <td><input type="text" name="to" /></td> 
    </tr> 
    <tr> 
      <td>抄送:</td> 
       <td><input type="text" name="copy" /></td> 
    </tr> 
    <tr> 
      <td>主题:</td> 
       <td><input type="text" name="title" /></td> 
    </tr> 
    <tr> 
      <td>信件内容:</td> 
      <td><textarea rows="10" cols="20" name="content" id="content"></textarea></td> 
    </tr> 
    <tr> 
      <td>附件:</td> 
      <td><input type='file' name='ufile' /></td> 
    </tr> 
    <tr> 
      <td>背景音乐:</td> 
      <td><input type='file' name='umusic' /></td> 
    </tr> 
    <tr> 
      <td>背景图片:</td><!-- 背景图片我们后台自己准备 --> 
      <td> 
        <select name="bgimg"> 
          <option value="1">一号</option> 
          <option value="2">二号</option> 
        </select> 
      </td> 
    </tr> 
    <tr align="right"> 
      <td colspan="2"><input type="submit" value="发 送"></td> 
    </tr> 
  </table>    
  </form> 
 </body> 
</html> 

 
 
为了防止乱码,会经过一个过滤器:

package org.filter; 
import java.io.ioexception; 
import javax.servlet.filter; 
import javax.servlet.filterchain; 
import javax.servlet.filterconfig; 
import javax.servlet.servletexception; 
import javax.servlet.servletrequest; 
import javax.servlet.servletresponse; 
/** 
 * 过滤器防止乱码 
 * @说明 
 * @author cuisuqiang 
 * @version 1.0 
 * @since 
 */ 
public class encodingfilter implements filter { 
  public void destroy() { 
  } 
  public void dofilter(servletrequest request, servletresponse response, 
      filterchain chain) throws ioexception, servletexception { 
    request.setcharacterencoding("utf-8"); 
    response.setcharacterencoding("utf-8"); 
    chain.dofilter(request, response); 
  } 
  public void init(filterconfig arg0) throws servletexception { 
  } 
} 


然后到servlet处理附件和信息,这里就不做异常处理了,出错直接报错:

package org.servlet; 
import java.io.*; 
import java.util.*; 
import javax.servlet.servletexception; 
import javax.servlet.http.httpservlet; 
import javax.servlet.http.httpservletrequest; 
import javax.servlet.http.httpservletresponse; 
import org.apache.commons.fileupload.fileitem; 
import org.apache.commons.fileupload.fileitemfactory; 
import org.apache.commons.fileupload.fileuploadexception; 
import org.apache.commons.fileupload.disk.diskfileitemfactory; 
import org.apache.commons.fileupload.servlet.servletfileupload; 
import org.entity.mailmodel; 
import org.mail.sendmail; 
/** 
 * 接收表单,处理附件,组装邮件对象,并调用发送接口 
 * @说明 在c盘创建临时文件 
 * @author cuisuqiang 
 * @version 1.0 
 * @since 
 */ 
@suppresswarnings("serial") 
public class sendmailservlet extends httpservlet { 
  @suppresswarnings( { "unchecked", "deprecation" }) 
  @override 
  protected void service(httpservletrequest request, 
      httpservletresponse response) throws servletexception, ioexception { 
    // 建立磁盘工厂 
    fileitemfactory factory = new diskfileitemfactory(); 
    // 表单域 
    servletfileupload upload = new servletfileupload(factory); 
    list<fileitem> items = null; 
    string bgimg = "1"; // 默认是第一个背景图片 
    try { 
      items = upload.parserequest(request); 
    } catch (fileuploadexception e) { 
      e.printstacktrace(); 
    } 
    mailmodel mail = new mailmodel(); 
    inputstream is = null; 
    for (fileitem item : items) { 
      if (!item.isformfield()) { // 如果是附件 
        if (item.getsize() > 0) { 
          is = item.getinputstream(); 
          string filename = ""; 
          if (item.getname().indexof("\\") == -1) { 
            filename = "c:\\tmp\\" + item.getname(); 
          } else { 
            filename = "c:\\tmp\\" + item.getname().substring(item.getname().lastindexof("\\")); 
          } 
          if (is.marksupported()) { 
            system.out.println("没有上传文件或文件已经删除"); 
          } else { 
            file file = new file(filename); 
            fileoutputstream fos = new fileoutputstream(file); // 建立输出流 
            byte[] buffer = new byte[8192]; // 每次读8k字节,大文件上传没有问题 
            int count = 0; 
            while ((count = is.read(buffer)) > 0) { // 循环写入到硬盘 
              fos.write(buffer, 0, count); 
            } 
            fos.close(); // 关闭输入输出流 
            is.close(); 
            if (item.getfieldname().equals("ufile")) { 
              mail.setfilepath(filename); 
            } else if (item.getfieldname().equals("umusic")) { 
              mail.setmusicpath(filename); 
            } 
          } 
        } 
      } else { // 处理文本信息 
        if (item.getfieldname().equals("title")) { 
          mail.settitle(item.getstring("utf-8")); 
        } else if (item.getfieldname().equals("content")) { 
          mail.setcontext(item.getstring("utf-8")); 
        } else if (item.getfieldname().equals("to")) { 
          mail.setto(item.getstring("utf-8")); 
        } else if (item.getfieldname().equals("copy")) { 
          mail.setcopy(item.getstring("utf-8")); 
        } else if (item.getfieldname().equals("bgimg")) { 
          bgimg = item.getstring("utf-8"); 
        } 
      } 
    } 
    string bgpath = request.getrealpath("/") + "\\images\\bg" + bgimg + ".jpg"; 
    mail.setbgpath(bgpath); 
    try { 
      sendmail.sendmail(mail); 
    } catch (exception e) { 
      e.printstacktrace(); 
    } 
    response.sendredirect(request.getcontextpath() + "/sendmail.jsp"); 
  } 
} 

 
 
这里也没有验证,接收到信息后组装一个邮件实体对象,传递到发送接口中发送:
实体,我就不写get和set方法了:

package org.entity; 
/** 
 * 一封邮件的对象 
 * @说明 
 * @author cuisuqiang 
 * @version 1.0 
 * @since 
 */ 
public class mailmodel { 
  /** 
   * 主键 
   */ 
  private int id; 
 
  /** 
   * 邮件标题 
   */ 
  private string title; 
 
  /** 
   * 发送给谁 
   */ 
  private string to; 
 
  /** 
   * 背景图片地址 
   */ 
  private string bgpath; 
 
  /** 
   * 抄送给谁 
   */ 
  private string copy; 
 
  /** 
   * 邮件内容 
   */ 
  private string context; 
 
  /** 
   * 附件地址 
   */ 
  private string filepath; 
  /** 
   * 背景音乐地址 
   */ 
  private string musicpath; 
} 

 
 
然后我们来看看核心处理类:
 

package org.mail; 
import java.io.file; 
import java.io.fileoutputstream; 
import java.io.outputstream; 
import java.util.date; 
import java.util.properties; 
import javax.activation.datahandler; 
import javax.activation.datasource; 
import javax.activation.filedatasource; 
import javax.mail.message; 
import javax.mail.session; 
import javax.mail.internet.internetaddress; 
import javax.mail.internet.mimebodypart; 
import javax.mail.internet.mimemessage; 
import javax.mail.internet.mimemultipart; 
import javax.mail.internet.mimeutility; 
import org.entity.mailmodel; 
/** 
 * 发送一封邮件 
 * @说明 注意这里并没有实际发送而是保存在了c盘临时文件中,真是发送的话,请参考我的博客 
 * @author cuisuqiang 
 * @version 1.0 
 * @since 
 */ 
public class sendmail { 
  public static void sendmail(mailmodel mail) throws exception { 
    properties props = new properties(); 
    props.put("mail.smtp.auth", "true"); 
    session session = session.getinstance(props); 
    message message = new mimemessage(session); 
    internetaddress from = new internetaddress(); 
    from.setpersonal(mimeutility.encodetext("风中落叶<cuisuqiang@163.com>")); 
    message.setfrom(from); 
    internetaddress to = new internetaddress(mail.getto()); 
    message.setrecipient(message.recipienttype.to, to); 
    // 是否抄送 
    if (null != mail.getcopy() && !"".equals(mail.getcopy())) { 
      internetaddress copy = new internetaddress(mail.getcopy()); 
      message.setrecipient(message.recipienttype.cc, copy); 
    } 
    message.setsubject(mimeutility.encodetext(mail.gettitle())); 
    message.setsentdate(new date()); 
    // 指定为混合关系 
    mimemultipart msgmultipart = new mimemultipart("mixed"); 
    message.setcontent(msgmultipart); 
    mimebodypart content = new mimebodypart(); 
    msgmultipart.addbodypart(content); 
    // 依赖关系 
    mimemultipart bodymultipart = new mimemultipart("related"); 
    content.setcontent(bodymultipart); 
    mimebodypart htmlpart = new mimebodypart(); 
    // 组装的顺序非常重要 
    bodymultipart.addbodypart(htmlpart); 
    mimebodypart in_bg = new mimebodypart(); 
    bodymultipart.addbodypart(in_bg); 
 
    datasource bgsou = new filedatasource(mail.getbgpath()); 
    datahandler bghd = new datahandler(bgsou); 
    in_bg.setdatahandler(bghd); 
    in_bg.setheader("content-location", "bg.jpg"); 
    // 是否使用了背景音乐 
    if (null == mail.getmusicpath() || "".equals(mail.getmusicpath())) { 
      string start = "<html><body background='bg.jpg'>"; 
      string end = "</body></html>"; 
      htmlpart.setcontent(start + mail.getcontext() + end,"text/html;charset=utf-8"); 
    } else { 
      mimebodypart in_part = new mimebodypart(); 
      bodymultipart.addbodypart(in_part); 
      datasource gifds = new filedatasource(mail.getmusicpath()); 
      datahandler gifdh = new datahandler(gifds); 
      in_part.setdatahandler(gifdh); 
      in_part.setheader("content-location", "bg.mp3"); 
      string start = "<html><head><bgsound src='bg.mp3' loop='-1'></head><body background='bg.jpg'>"; 
      string end = "</body></html>"; 
      htmlpart.setcontent(start + mail.getcontext() + end,"text/html;charset=utf-8"); 
    } 
    // 组装附件 
    if (null != mail.getfilepath() && !"".equals(mail.getfilepath())) {      
      mimebodypart file = new mimebodypart(); 
      filedatasource file_datasource = new filedatasource(mail 
          .getfilepath()); 
      datahandler dh = new datahandler(file_datasource); 
      file.setdatahandler(dh); 
      file.setfilename(mimeutility.encodetext(dh.getname())); 
      msgmultipart.addbodypart(file); 
    } 
    message.savechanges(); 
    // 保存邮件 
    outputstream ips = new fileoutputstream("c:\\tmp\\test.eml"); 
    message.writeto(ips); 
    ips.close(); 
    system.out.println("------------发送完毕------------"); 
    // 删除临时文件 
    if (null != mail.getmusicpath() && !"".equals(mail.getmusicpath())) { 
      file file = new file(mail.getmusicpath()); 
      file.delete(); 
    } 
    if (null != mail.getfilepath() && !"".equals(mail.getfilepath())) { 
      file file = new file(mail.getfilepath()); 
      file.delete(); 
    } 
  } 
} 

我们把邮件发送了c盘,可以到c盘查看,如果需要实际发送,可以参考我的其他博客,有专门说明!

使用Java发送带附件的附件的示例