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

      2019-12-20 09:09      JAVA编程
这篇文章主要介绍了使用Java发送带附件的附件的方法,使用到了JavaMail这个API,需要的朋友可以参考下

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

 

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盘查看,如果需要实际发送,可以参考我的其他博客,有专门说明!