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


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

JavaMail邮件发送-能发送附件和带背景音乐的邮件的小系统_第1张图片

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

Java代码 收藏代码
  1. <%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
  2. <%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
  3. <%
  4. Stringpath=request.getContextPath();
  5. StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  6. %>
  7. <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
  8. <html>
  9. <head>
  10. <basehref="<%=basePath%>">
  11. <title>发送邮件</title>
  12. <metahttp-equiv="pragma"content="no-cache">
  13. <metahttp-equiv="cache-control"content="no-cache">
  14. <metahttp-equiv="expires"content="0">
  15. <scripttype="text/javascript"src="fckeditor/fckeditor.js"></script>
  16. <scripttype="text/javascript">
  17. window.onload=function(){
  18. varoFCKeditor=newFCKeditor('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. <formaction="SendMailServlet"method="post"enctype="multipart/form-data">
  36. <table>
  37. <tr>
  38. <td>收件人:</td>
  39. <td><inputtype="text"name="to"/></td>
  40. </tr>
  41. <tr>
  42. <td>抄送:</td>
  43. <td><inputtype="text"name="copy"/></td>
  44. </tr>
  45. <tr>
  46. <td>主题:</td>
  47. <td><inputtype="text"name="title"/></td>
  48. </tr>
  49. <tr>
  50. <td>信件内容:</td>
  51. <td><textarearows="10"cols="20"name="content"id="content"></textarea></td>
  52. </tr>
  53. <tr>
  54. <td>附件:</td>
  55. <td><inputtype='file'name='ufile'/></td>
  56. </tr>
  57. <tr>
  58. <td>背景音乐:</td>
  59. <td><inputtype='file'name='umusic'/></td>
  60. </tr>
  61. <tr>
  62. <td>背景图片:</td><!--背景图片我们后台自己准备-->
  63. <td>
  64. <selectname="bgimg">
  65. <optionvalue="1">一号</option>
  66. <optionvalue="2">二号</option>
  67. </select>
  68. </td>
  69. </tr>
  70. <tralign="right">
  71. <tdcolspan="2"><inputtype="submit"value="发送"></td>
  72. </tr>
  73. </table>
  74. </form>
  75. </body>
  76. </html>

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

Java代码 收藏代码
  1. packageorg.filter;
  2. importjava.io.IOException;
  3. importjavax.servlet.Filter;
  4. importjavax.servlet.FilterChain;
  5. importjavax.servlet.FilterConfig;
  6. importjavax.servlet.ServletException;
  7. importjavax.servlet.ServletRequest;
  8. importjavax.servlet.ServletResponse;
  9. /**
  10. *过滤器防止乱码
  11. *@说明
  12. *@authorcuisuqiang
  13. *@version1.0
  14. *@since
  15. */
  16. publicclassEncodingFilterimplementsFilter{
  17. publicvoiddestroy(){
  18. }
  19. publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,
  20. FilterChainchain)throwsIOException,ServletException{
  21. request.setCharacterEncoding("UTF-8");
  22. response.setCharacterEncoding("UTF-8");
  23. chain.doFilter(request,response);
  24. }
  25. publicvoidinit(FilterConfigarg0)throwsServletException{
  26. }
  27. }

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

Java代码 收藏代码
  1. packageorg.servlet;
  2. importjava.io.*;
  3. importjava.util.*;
  4. importjavax.servlet.ServletException;
  5. importjavax.servlet.http.HttpServlet;
  6. importjavax.servlet.http.HttpServletRequest;
  7. importjavax.servlet.http.HttpServletResponse;
  8. importorg.apache.commons.fileupload.FileItem;
  9. importorg.apache.commons.fileupload.FileItemFactory;
  10. importorg.apache.commons.fileupload.FileUploadException;
  11. importorg.apache.commons.fileupload.disk.DiskFileItemFactory;
  12. importorg.apache.commons.fileupload.servlet.ServletFileUpload;
  13. importorg.entity.MailModel;
  14. importorg.mail.SendMail;
  15. /**
  16. *接收表单,处理附件,组装邮件对象,并调用发送接口
  17. *@说明在C盘创建临时文件
  18. *@authorcuisuqiang
  19. *@version1.0
  20. *@since
  21. */
  22. @SuppressWarnings("serial")
  23. publicclassSendMailServletextendsHttpServlet{
  24. @SuppressWarnings({"unchecked","deprecation"})
  25. @Override
  26. protectedvoidservice(HttpServletRequestrequest,
  27. HttpServletResponseresponse)throwsServletException,IOException{
  28. //建立磁盘工厂
  29. FileItemFactoryfactory=newDiskFileItemFactory();
  30. //表单域
  31. ServletFileUploadupload=newServletFileUpload(factory);
  32. List<FileItem>items=null;
  33. Stringbgimg="1";//默认是第一个背景图片
  34. try{
  35. items=upload.parseRequest(request);
  36. }catch(FileUploadExceptione){
  37. e.printStackTrace();
  38. }
  39. MailModelmail=newMailModel();
  40. InputStreamis=null;
  41. for(FileItemitem:items){
  42. if(!item.isFormField()){//如果是附件
  43. if(item.getSize()>0){
  44. is=item.getInputStream();
  45. Stringfilename="";
  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. Filefile=newFile(filename);
  55. FileOutputStreamfos=newFileOutputStream(file);//建立输出流
  56. byte[]buffer=newbyte[8192];//每次读8K字节,大文件上传没有问题
  57. intcount=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. }elseif(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. }elseif(item.getFieldName().equals("content")){
  74. mail.setContext(item.getString("UTF-8"));
  75. }elseif(item.getFieldName().equals("to")){
  76. mail.setTo(item.getString("UTF-8"));
  77. }elseif(item.getFieldName().equals("copy")){
  78. mail.setCopy(item.getString("UTF-8"));
  79. }elseif(item.getFieldName().equals("bgimg")){
  80. bgimg=item.getString("UTF-8");
  81. }
  82. }
  83. }
  84. StringbgPath=request.getRealPath("/")+"\\images\\bg"+bgimg+".jpg";
  85. mail.setBgPath(bgPath);
  86. try{
  87. SendMail.sendMail(mail);
  88. }catch(Exceptione){
  89. e.printStackTrace();
  90. }
  91. response.sendRedirect(request.getContextPath()+"/sendmail.jsp");
  92. }
  93. }

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

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

Java代码 收藏代码
  1. packageorg.entity;
  2. /**
  3. *一封邮件的对象
  4. *@说明
  5. *@authorcuisuqiang
  6. *@version1.0
  7. *@since
  8. */
  9. publicclassMailModel{
  10. /**
  11. *主键
  12. */
  13. privateintid;
  14. /**
  15. *邮件标题
  16. */
  17. privateStringtitle;
  18. /**
  19. *发送给谁
  20. */
  21. privateStringto;
  22. /**
  23. *背景图片地址
  24. */
  25. privateStringbgPath;
  26. /**
  27. *抄送给谁
  28. */
  29. privateStringcopy;
  30. /**
  31. *邮件内容
  32. */
  33. privateStringcontext;
  34. /**
  35. *附件地址
  36. */
  37. privateStringfilePath;
  38. /**
  39. *背景音乐地址
  40. */
  41. privateStringmusicPath;
  42. }

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

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

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

JavaMail邮件发送-能发送附件和带背景音乐的邮件的小系统_第2张图片

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

你可能感兴趣的:(javamail)