通过commons-email组件发送带有附件的邮件

上传文件页面sendAttachmentMail.jsp

<form id="form1" name="form1" method="post" action="<%=request.getContextPath()%>/servlet/sendAttachmentMail" enctype="multipart/form-data">
  <table width="516" height="253" border="0" align="center">
    <tr>
      <td>收件人:</td>
      <td><label>
        <input type="text" name="to" id="to" />
      </label></td>
    </tr>
    <tr>
      <td>发件人:</td>
      <td><label>
        <input type="text" name="from" id="from" />
      </label></td>
    </tr>
    <tr>
      <td>主题:</td>
      <td><label>
        <input type="text" name="subject" id="subject" />
      </label></td>
    </tr>
    <tr>
      <td>选择附件:</td>
      <td><label>
        <input type="file" name="attachment" id="file" />
      </label></td>
    </tr>
    <tr>
      <td>内容:</td>
      <td><label>
        <textarea name="content" id="content" cols="45" rows="8"></textarea>
      </label></td>
    </tr>
    <tr>
      <td><label>
        <input type="submit" name="button" id="button" value="提交" />
      </label></td>
      <td><label>
        <input type="reset" name="button2" id="button2" value="重置" />
      </label></td>
    </tr>
  </table>
</form>

 web.xml中添加servlet信息

<servlet>
    <servlet-name>SendAttachmentMailServlet</servlet-name>
    <servlet-class>com.email.SendAttachmentMailServlet</servlet-class>
    <init-param>
    	<param-name>savePath</param-name>
    	<param-value>uploads</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>SendAttachmentMailServlet</servlet-name>
    <url-pattern>/servlet/sendAttachmentMail</url-pattern>
  </servlet-mapping>

 Servlet类SendAttachmentMailServlet.java中涉及到附件,所以有个上传文件的方法doAttachment,及初始化方法得到文件保存路径参数!!

/**
 * 通过web邮箱服务器发送邮件
 * 
 * @author lrq413
 *
 */
public class SendAttachmentMailServlet extends HttpServlet {

	private static final long serialVersionUID = -1408700020471642036L;
	//定义上下文sc、文件保存路径savePath,表单内容parameters
	private ServletContext sc;
	private String savePath;
	private Map<String, String> parameters = new HashMap<String, String>();

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);

	}

	/**
	 * 处理表单信息,并发送邮件
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("doPost");
//		处理请求页面中文字符集
		request.setCharacterEncoding("gbk");
		response.setContentType("text/html; charset=gbk");
		//得到表单中附件
		File file = this.doAttachment(request);
		//包含附件功能的邮件定义
		MultiPartEmail email = new MultiPartEmail();
		//设置邮件发送的服务器
		email.setHostName("smtp.163.com");
		//邮件发送验证用户名,密码
		email.setAuthentication("lrq41234", "8259698");
		//设置邮件接收字符集
		email.setCharset("gbk");

		try {
			//设置邮件信息,从表单中取得邮箱发送人、接收人、主题、内容
			email.addTo(parameters.get("to"));
			email.setFrom(parameters.get("from"));
			email.setSubject(parameters.get("subject"));
			email.setMsg(parameters.get("content"));
			if (file != null) {
				//邮件添加附件,设置邮件附件的路径、类型、名称
				EmailAttachment attachment = new EmailAttachment();
				attachment.setPath(file.getPath());
				attachment.setDisposition(EmailAttachment.ATTACHMENT);
				attachment.setName(file.getName());
				email.attach(attachment);
			}
			//发送邮件
			email.send();
			request.setAttribute("sendmail.message", "success");
		} catch (EmailException e) {
			e.printStackTrace();
			request.setAttribute("sendmail.message", "error");
		}
		//转发到结果页面
		request.getRequestDispatcher("/sendResult.jsp").forward(request,
				response);

	}

	/**
	 * 附件上传
	 * 
	 * @param request
	 * @return File
	 * @throws ServletException
	 * @throws IOException
	 */
	public File doAttachment(HttpServletRequest request)
			throws ServletException, IOException {
		File file = null;
		//定义文件上传相关对象实例
		request.setCharacterEncoding("gbk");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);

		try {
			//从请求表单中得到文件上传信息
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();
				//将表单中信息存入parameters集合中,Map集合中存放表单名/值
				if (item.isFormField()) {
					parameters
							.put(item.getFieldName(), item.getString("gbk"));
					System.out.println("parameters = " + parameters);
				} else {
					//文件不为空,上传文件
					if (item.getName() != null && !item.getName().equals("")) {
						File tempFile = new File(item.getName());
						file = new File(sc.getRealPath("/") + savePath,
								tempFile.getName());
						item.write(file);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("upload.message", "成功");
		}
		return file;
	}

	/**
	 * 初始化方法,
	 */
	public void init(ServletConfig config) {
		//从配置文件中取得初始化参数
		savePath = config.getInitParameter("savePath");
		sc = config.getServletContext();
	}

}

 该实现方法是将附件上传到服务器中,再从服务器中将邮件并附件一起发出!!!最好是对方发送完邮件后,将附件信息删除!!

你可能感兴趣的:(jsp,Web,servlet)