JSP+Servlet实现发送邮件

项目介绍

同前参考JSP程序设计教程(第二版)教材实现傻瓜式发送邮件功能,适合初学JSP的程序猿,日后可在此基础上扩展为注册邮箱验证;在此对期间遇到的问题及部分页面展示如下

遇到的问题

1、邮箱授权码与密码混用

下图为遇到的第一个问题
邮箱授权码出错
原因在于这里password为邮箱的授权码而非密码,采用了密码来代替授权码于是导致验证授权码不正确而出现如上图错误代码,所以需要设置并输入正确的授权码,QQ邮箱授权码的设置见下图
QQ邮箱设置授权码
其余邮箱的授权码设置方法也类似

2、字符集出错

在send.java对邮件的发送处理页面由于字符集设置的顺序问题导致js弹出的错误信息无法正常识别显示中文,下图39行输出函数的定义应放在36/37行之后,否则就会出现输出中文编码错误的问题。
设置字符集

主要页面展示

写邮件界面

主要页面代码展示

1.Index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>电子邮件发送</title>
<script type="text/javascript">
	function Checkform(myform){
		for(i=0;i<myform.length;i++){
			if(myform.elements[i].value==""){
				alert(myform.elements[i].title+"不能为空!");
				myform.elements[i].focus();
				return false;
			}
		}
	}
</script>
</head>
<body>
<form action="Send" method="post" name="form1" id="form" onsubmit="return Checkform(form1)">
		收件人:<input type="text" name="receiver" title="收件人" id="receiver" size="60" value="1324466456@qq.com"><p>
		发件人:<input type="text" name="sender" title="发件人" id="sender" size="60"><p>
		授权码:<input type="password" name="password" id="password" title="邮箱授权码" size="60"><p>&nbsp;&nbsp;&nbsp;&nbsp;题:<input type="text" name="subject" id="subject" title="邮件主题" size="60"><p>&nbsp;&nbsp;&nbsp;&nbsp;容:<textarea rows="7" cols="59" name="content" id="content" title="邮件内容"></textarea><p>
		<input type="submit" name="submit" value="发送">
		<input type="reset" name="reset" value="重置">
</form>
</body>
</html>

2.Send.java

package Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Send
 */
@WebServlet("/Send")
public class Send extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Send() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();//必须定义在37,38行设置编码格式后边,否则输出中文为???
		String sender=request.getParameter("sender");
		String password=request.getParameter("password");
		String receiver=request.getParameter("receiver");
		String subject=request.getParameter("subject");
		String content=request.getParameter("content");
		//生成SMTP的主机名称
		int n=sender.indexOf("@");
		int m=sender.length();
		String mailserver="smtp."+sender.substring(n+1, m);
		//建立邮件会话
		Properties pro=new Properties();
		pro.put("mail.smtp.host", mailserver);
		pro.put("mail.smtp.auth", true);
		Session sess=Session.getInstance(pro);
		sess.setDebug(true);
		MimeMessage message=new MimeMessage(sess);//新建一个消息对象
		try {
			//设置发件人
			InternetAddress sender_address=new InternetAddress(sender);
			message.setFrom(sender_address);
			//设置收件人
			InternetAddress receiver_address=new InternetAddress(receiver);
			message.setRecipient(javax.mail.Message.RecipientType.TO,receiver_address);
//			message.add
			message.setSubject(subject);//设置主题
			message.setText(content);//设置内容  不是setContent
			message.setSentDate(new Date());//设置发送时间
			//发送邮件
			System.out.println("地址为:"+mailserver+" "+sender+" "+password);
			message.saveChanges();//保证报头域同会话内容保持一致
			Transport transport=sess.getTransport("smtp");
			transport.connect(mailserver, sender, password);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
			out.print("<script>alert('邮件已发送!');window.location.href='Index.jsp';</script>");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("发送邮件产生的错误:"+e.getMessage());
			out.print("<script>alert('邮件发送失败!');window.location.href='Index.jsp';</script>");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页