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

http://cuisuqiang.iteye.com/blog/1750866

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

  • 博客分类:
  • J2EE

这里使用的是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.οnlοad=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> 
<%@ 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.οnlοad=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>

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

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.     } 
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处理附件和信息,这里就不做异常处理了,出错直接报错:

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.     } 
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方法了:

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; 
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;
}

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

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

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

http://cuisuqiang.iteye.com/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值