JavaMail邮件发送-能发送附件和带背景音乐的邮件的小系统

来源:互联网 发布:网络人旗舰版破解版 编辑:程序博客网 时间:2024/05/28 18:43

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

 

 

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

 

Java代码  收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.     <title>发送邮件</title>  
  12.     <meta http-equiv="pragma" content="no-cache">  
  13.     <meta http-equiv="cache-control" content="no-cache">  
  14.     <meta http-equiv="expires" content="0">      
  15.     <script type="text/javascript" src="fckeditor/fckeditor.js"></script>  
  16.     <script type="text/javascript">  
  17.     window.onload=function(){  
  18.         var oFCKeditor = new FCKeditor( 'content' ) ;  
  19.         //编译器基本路径  
  20.         oFCKeditor.BasePath = "/pro_04/fckeditor/";  
  21.         //高度  
  22.         oFCKeditor.Width=800;  
  23.         //宽度  
  24.         oFCKeditor.Height=300;  
  25.         //工具条集合名称(Default,Basic或自己制定,关于FCK的使用,博客内有专门文章)  
  26.         //具体的配置可以将默认显示出来然后到FCK目录里的fckconfig.js里  
  27.         //FCKConfig.ToolbarSets["Default"]数组中去除不要的功能一共63个功能属性  
  28.         //oFCKeditor.ToolbarSet="Basic";  
  29.         oFCKeditor.ReplaceTextarea() ;            
  30.     }  
  31.     </script>  
  32.   </head>  
  33.   <body>  
  34.     <!-- 注意表单格式,这里需要上传附件 -->  
  35.     <form action="SendMailServlet" method="post"  enctype="multipart/form-data">  
  36.     <table>  
  37.         <tr>  
  38.             <td>收件人:</td>  
  39.              <td><input type="text" name="to" /></td>  
  40.         </tr>  
  41.         <tr>  
  42.             <td>抄送:</td>  
  43.              <td><input type="text" name="copy" /></td>  
  44.         </tr>  
  45.         <tr>  
  46.             <td>主题:</td>  
  47.              <td><input type="text" name="title" /></td>  
  48.         </tr>  
  49.         <tr>  
  50.             <td>信件内容:</td>  
  51.             <td><textarea rows="10" cols="20" name="content" id="content"></textarea></td>  
  52.         </tr>  
  53.         <tr>  
  54.             <td>附件:</td>  
  55.             <td><input type='file' name='ufile' /></td>  
  56.         </tr>  
  57.         <tr>  
  58.             <td>背景音乐:</td>  
  59.             <td><input type='file' name='umusic' /></td>  
  60.         </tr>  
  61.         <tr>  
  62.             <td>背景图片:</td><!-- 背景图片我们后台自己准备 -->  
  63.             <td>  
  64.                 <select name="bgimg">  
  65.                     <option value="1">一号</option>  
  66.                     <option value="2">二号</option>  
  67.                 </select>  
  68.             </td>  
  69.         </tr>  
  70.         <tr align="right">  
  71.             <td colspan="2"><input type="submit" value="发 送"></td>  
  72.         </tr>  
  73.     </table>        
  74.     </form>  
  75.   </body>  
  76. </html>  
 

 

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

 

Java代码  收藏代码
  1. package org.filter;  
  2. import java.io.IOException;  
  3. import javax.servlet.Filter;  
  4. import javax.servlet.FilterChain;  
  5. import javax.servlet.FilterConfig;  
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.ServletRequest;  
  8. import javax.servlet.ServletResponse;  
  9. /** 
  10.  * 过滤器防止乱码 
  11.  * @说明  
  12.  * @author cuisuqiang 
  13.  * @version 1.0 
  14.  * @since 
  15.  */  
  16. public class EncodingFilter implements Filter {  
  17.     public void destroy() {  
  18.     }  
  19.     public void doFilter(ServletRequest request, ServletResponse response,  
  20.             FilterChain chain) throws IOException, ServletException {  
  21.         request.setCharacterEncoding("UTF-8");  
  22.         response.setCharacterEncoding("UTF-8");  
  23.         chain.doFilter(request, response);  
  24.     }  
  25.     public void init(FilterConfig arg0) throws ServletException {  
  26.     }  
  27. }  
 

 

 

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

 

Java代码  收藏代码
  1. package org.servlet;  
  2. import java.io.*;  
  3. import java.util.*;  
  4. import javax.servlet.ServletException;  
  5. import javax.servlet.http.HttpServlet;  
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8. import org.apache.commons.fileupload.FileItem;  
  9. import org.apache.commons.fileupload.FileItemFactory;  
  10. import org.apache.commons.fileupload.FileUploadException;  
  11. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  12. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  13. import org.entity.MailModel;  
  14. import org.mail.SendMail;  
  15. /** 
  16.  * 接收表单,处理附件,组装邮件对象,并调用发送接口 
  17.  * @说明 在C盘创建临时文件 
  18.  * @author cuisuqiang 
  19.  * @version 1.0 
  20.  * @since 
  21.  */  
  22. @SuppressWarnings("serial")  
  23. public class SendMailServlet extends HttpServlet {  
  24.     @SuppressWarnings( { "unchecked""deprecation" })  
  25.     @Override  
  26.     protected void service(HttpServletRequest request,  
  27.             HttpServletResponse response) throws ServletException, IOException {  
  28.         // 建立磁盘工厂  
  29.         FileItemFactory factory = new DiskFileItemFactory();  
  30.         // 表单域  
  31.         ServletFileUpload upload = new ServletFileUpload(factory);  
  32.         List<FileItem> items = null;  
  33.         String bgimg = "1"// 默认是第一个背景图片  
  34.         try {  
  35.             items = upload.parseRequest(request);  
  36.         } catch (FileUploadException e) {  
  37.             e.printStackTrace();  
  38.         }  
  39.         MailModel mail = new MailModel();  
  40.         InputStream is = null;  
  41.         for (FileItem item : items) {  
  42.             if (!item.isFormField()) { // 如果是附件  
  43.                 if (item.getSize() > 0) {  
  44.                     is = item.getInputStream();  
  45.                     String filename = "";  
  46.                     if (item.getName().indexOf("\\") == -1) {  
  47.                         filename = "c:\\tmp\\" + item.getName();  
  48.                     } else {  
  49.                         filename = "c:\\tmp\\" + item.getName().substring(item.getName().lastIndexOf("\\"));  
  50.                     }  
  51.                     if (is.markSupported()) {  
  52.                         System.out.println("没有上传文件或文件已经删除");  
  53.                     } else {  
  54.                         File file = new File(filename);  
  55.                         FileOutputStream fos = new FileOutputStream(file); // 建立输出流  
  56.                         byte[] buffer = new byte[8192]; // 每次读8K字节,大文件上传没有问题  
  57.                         int count = 0;  
  58.                         while ((count = is.read(buffer)) > 0) { // 循环写入到硬盘  
  59.                             fos.write(buffer, 0, count);  
  60.                         }  
  61.                         fos.close(); // 关闭输入输出流  
  62.                         is.close();  
  63.                         if (item.getFieldName().equals("ufile")) {  
  64.                             mail.setFilePath(filename);  
  65.                         } else if (item.getFieldName().equals("umusic")) {  
  66.                             mail.setMusicPath(filename);  
  67.                         }  
  68.                     }  
  69.                 }  
  70.             } else { // 处理文本信息  
  71.                 if (item.getFieldName().equals("title")) {  
  72.                     mail.setTitle(item.getString("UTF-8"));  
  73.                 } else if (item.getFieldName().equals("content")) {  
  74.                     mail.setContext(item.getString("UTF-8"));  
  75.                 } else if (item.getFieldName().equals("to")) {  
  76.                     mail.setTo(item.getString("UTF-8"));  
  77.                 } else if (item.getFieldName().equals("copy")) {  
  78.                     mail.setCopy(item.getString("UTF-8"));  
  79.                 } else if (item.getFieldName().equals("bgimg")) {  
  80.                     bgimg = item.getString("UTF-8");  
  81.                 }  
  82.             }  
  83.         }  
  84.         String bgPath = request.getRealPath("/") + "\\images\\bg" + bgimg + ".jpg";  
  85.         mail.setBgPath(bgPath);  
  86.         try {  
  87.             SendMail.sendMail(mail);  
  88.         } catch (Exception e) {  
  89.             e.printStackTrace();  
  90.         }  
  91.         response.sendRedirect(request.getContextPath() + "/sendmail.jsp");  
  92.     }  
  93. }  
 

 

这里也没有验证,接收到信息后组装一个邮件实体对象,传递到发送接口中发送:

实体,我就不写get和set方法了:

 

Java代码  收藏代码
  1. package org.entity;  
  2. /** 
  3.  * 一封邮件的对象 
  4.  * @说明  
  5.  * @author cuisuqiang 
  6.  * @version 1.0 
  7.  * @since 
  8.  */  
  9. public class MailModel {  
  10.     /** 
  11.      * 主键 
  12.      */  
  13.     private int id;  
  14.   
  15.     /** 
  16.      * 邮件标题 
  17.      */  
  18.     private String title;  
  19.   
  20.     /** 
  21.      * 发送给谁 
  22.      */  
  23.     private String to;  
  24.   
  25.     /** 
  26.      * 背景图片地址 
  27.      */  
  28.     private String bgPath;  
  29.   
  30.     /** 
  31.      * 抄送给谁 
  32.      */  
  33.     private String copy;  
  34.   
  35.     /** 
  36.      * 邮件内容 
  37.      */  
  38.     private String context;  
  39.   
  40.     /** 
  41.      * 附件地址 
  42.      */  
  43.     private String filePath;  
  44.     /** 
  45.      * 背景音乐地址 
  46.      */  
  47.     private String musicPath;  
  48. }  
 

 

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

 

Java代码  收藏代码
  1. package org.mail;  
  2. import java.io.File;  
  3. import java.io.FileOutputStream;  
  4. import java.io.OutputStream;  
  5. import java.util.Date;  
  6. import java.util.Properties;  
  7. import javax.activation.DataHandler;  
  8. import javax.activation.DataSource;  
  9. import javax.activation.FileDataSource;  
  10. import javax.mail.Message;  
  11. import javax.mail.Session;  
  12. import javax.mail.internet.InternetAddress;  
  13. import javax.mail.internet.MimeBodyPart;  
  14. import javax.mail.internet.MimeMessage;  
  15. import javax.mail.internet.MimeMultipart;  
  16. import javax.mail.internet.MimeUtility;  
  17. import org.entity.MailModel;  
  18. /** 
  19.  * 发送一封邮件 
  20.  * @说明 注意这里并没有实际发送而是保存在了C盘临时文件中,真是发送的话,请参考我的博客 
  21.  * @author cuisuqiang 
  22.  * @version 1.0 
  23.  * @since 
  24.  */  
  25. public class SendMail {  
  26.     public static void sendMail(MailModel mail) throws Exception {  
  27.         Properties props = new Properties();  
  28.         props.put("mail.smtp.auth""true");  
  29.         Session session = Session.getInstance(props);  
  30.         Message message = new MimeMessage(session);  
  31.         InternetAddress from = new InternetAddress();  
  32.         from.setPersonal(MimeUtility.encodeText("风中落叶<cuisuqiang@163.com>"));  
  33.         message.setFrom(from);  
  34.         InternetAddress to = new InternetAddress(mail.getTo());  
  35.         message.setRecipient(Message.RecipientType.TO, to);  
  36.         // 是否抄送  
  37.         if (null != mail.getCopy() && !"".equals(mail.getCopy())) {  
  38.             InternetAddress copy = new InternetAddress(mail.getCopy());  
  39.             message.setRecipient(Message.RecipientType.CC, copy);  
  40.         }  
  41.         message.setSubject(MimeUtility.encodeText(mail.getTitle()));  
  42.         message.setSentDate(new Date());  
  43.         // 指定为混合关系  
  44.         MimeMultipart msgMultipart = new MimeMultipart("mixed");  
  45.         message.setContent(msgMultipart);  
  46.         MimeBodyPart content = new MimeBodyPart();  
  47.         msgMultipart.addBodyPart(content);  
  48.         // 依赖关系  
  49.         MimeMultipart bodyMultipart = new MimeMultipart("related");  
  50.         content.setContent(bodyMultipart);  
  51.         MimeBodyPart htmlPart = new MimeBodyPart();  
  52.         // 组装的顺序非常重要  
  53.         bodyMultipart.addBodyPart(htmlPart);  
  54.         MimeBodyPart in_bg = new MimeBodyPart();  
  55.         bodyMultipart.addBodyPart(in_bg);  
  56.   
  57.         DataSource bgsou = new FileDataSource(mail.getBgPath());  
  58.         DataHandler bghd = new DataHandler(bgsou);  
  59.         in_bg.setDataHandler(bghd);  
  60.         in_bg.setHeader("Content-Location""bg.jpg");  
  61.         // 是否使用了背景音乐  
  62.         if (null == mail.getMusicPath() || "".equals(mail.getMusicPath())) {  
  63.             String start = "<html><body background='bg.jpg'>";  
  64.             String end = "</body></html>";  
  65.             htmlPart.setContent(start + mail.getContext() + end,"text/html;charset=UTF-8");  
  66.         } else {  
  67.             MimeBodyPart in_Part = new MimeBodyPart();  
  68.             bodyMultipart.addBodyPart(in_Part);  
  69.             DataSource gifds = new FileDataSource(mail.getMusicPath());  
  70.             DataHandler gifdh = new DataHandler(gifds);  
  71.             in_Part.setDataHandler(gifdh);  
  72.             in_Part.setHeader("Content-Location""bg.mp3");  
  73.             String start = "<html><head><bgsound src='bg.mp3' loop='-1'></head><body background='bg.jpg'>";  
  74.             String end = "</body></html>";  
  75.             htmlPart.setContent(start + mail.getContext() + end,"text/html;charset=UTF-8");  
  76.         }  
  77.         // 组装附件  
  78.         if (null != mail.getFilePath() && !"".equals(mail.getFilePath())) {           
  79.             MimeBodyPart file = new MimeBodyPart();  
  80.             FileDataSource file_datasource = new FileDataSource(mail  
  81.                     .getFilePath());  
  82.             DataHandler dh = new DataHandler(file_datasource);  
  83.             file.setDataHandler(dh);  
  84.             file.setFileName(MimeUtility.encodeText(dh.getName()));  
  85.             msgMultipart.addBodyPart(file);  
  86.         }  
  87.         message.saveChanges();  
  88.         // 保存邮件  
  89.         OutputStream ips = new FileOutputStream("C:\\tmp\\test.eml");  
  90.         message.writeTo(ips);  
  91.         ips.close();  
  92.         System.out.println("------------发送完毕------------");  
  93.         // 删除临时文件  
  94.         if (null != mail.getMusicPath() && !"".equals(mail.getMusicPath())) {  
  95.             File file = new File(mail.getMusicPath());  
  96.             file.delete();  
  97.         }  
  98.         if (null != mail.getFilePath() && !"".equals(mail.getFilePath())) {  
  99.             File file = new File(mail.getFilePath());  
  100.             file.delete();  
  101.         }  
  102.     }  
  103. }  
 

 

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

 

 

 

请您到ITEYE网站看原创,谢谢!