您的位置:首页 > 编程语言 > Java开发

JavaMail发送邮件

2016-05-19 09:34 429 查看
当我们注册一个网站的时候,往往要通过邮件验证才可注册成功;或者我们忘记密码时,网站就会通过您的邮箱给您发送一份邮件,将密码告诉你。这些系统自动发送邮件的操作都可以通过Java中的JavaMail完成。

项目的结构如下:




代码如下:
######################################################################
MyAuthenticator.java

######################################################################
package bean;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MyAuthenticator extends Authenticator { 

    private String userName; 

    private String password; 

 

    public MyAuthenticator(String
userName, String password){ 

        this.userName=
userName; 

        this.password=
password; 

    } 

 

    @Override 

    protected PasswordAuthentication getPasswordAuthentication() { 

        return new PasswordAuthentication(userName, password); 

    } 



######################################################################
RegisterServlet.java

######################################################################
package control;
import java.io.IOException; 
import java.util.Date; 
import java.util.Properties; 

 
import javax.mail.Address; 
import javax.mail.Authenticator; 
import javax.mail.Message.RecipientType; 
import javax.mail.MessagingException; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeMessage; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpSession; 

import bean.MyAuthenticator;   

 
public
class
 RegisterServlet extends HttpServlet { 

    private static final long serialVersionUID = 1L; 

 

    public void doGet(HttpServletRequest
request, HttpServletResponse response) 

            throws ServletException, IOException {

       

        //获取前台用户输入的邮箱以及用户名

        String toMail = request.getParameter("email"); 

        String registerName = request.getParameter("userName"); 

         

        // 创建一个临时用户注册ID

        String registerId = "" + Math.random() * Math.random(); 

        //邮件发送成功后,用户点在邮箱中点击这个链接回到注册网站。        

        String url = "http://localhost:8080/JavaMailChecker/servlet/MailBackServlet?registerId=" + registerId;

         

        // 设置session值,将用户ID和用户名保存在session值中

        HttpSession httpSession = request.getSession(); 

        httpSession.setAttribute(registerId, registerName); 

        // 设置session的有效时间,为10分钟,10分钟内没有点击链接的话,注册将失败

        httpSession.setMaxInactiveInterval(600); 

         

        // 设置邮箱的属性

        Properties props = new Properties();

        // 若发送者的邮箱为其他服务器,例如163邮箱的话,就将下面服务器的值改为smtp.163.com

        props.setProperty("mail.smtp.host", "smtp.qq.com"); 

        props.setProperty("mail.smtp.auth", "true"); 

        // 设置验证值,发送者的邮箱要通过验证才可以发送邮件

        // 设置发送者的邮箱和密码,对其进行修改

        String userName = "aaaa@qq.com"; 

        String password = "00000000"; 

        Authenticator authenticator = new MyAuthenticator(userName, password); 

         

        javax.mail.Session session = javax.mail.Session.getDefaultInstance(props,authenticator); 

        session.setDebug(true); 

         

        try

                    Address from = new InternetAddress(userName); 

                    Address to = new InternetAddress(toMail); 

                     

                    MimeMessage msg = new MimeMessage(session); 

                    msg.setFrom(from); 

                    msg.setSubject("###网站注册"); 

                    msg.setSentDate(new Date()); 

                    msg.setContent("点击<a href='" + url + "'>" + url + "</a>完成注册!", "text/html;charset=utf-8"); 

                    msg.setRecipient(RecipientType.TO, to);  

                    Transport.send(msg); 

        } catch(MessagingException e){ 

            e.printStackTrace(); 

        } 

         

        request.getRequestDispatcher("/sendMailSuccess.jsp").forward(request, response); 

    } 

 

    public void doPost(HttpServletRequest
request, HttpServletResponse response) 

            throws ServletException, IOException { 

        doGet(request, response); 

    } 



######################################################################
MailBackServlet.java

######################################################################
package control;
import java.io.IOException; 

import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

 
public
class
 MailBackServlet extends HttpServlet { 

    private
static final long
 serialVersionUID = 1L; 

 

    public void doGet(HttpServletRequest
request, HttpServletResponse response) 

            throws ServletException,
IOException { 

        String registerID = request.getParameter("registerId"); 

        if(registerID == null){ 

            request.getRequestDispatcher("/index.jsp").forward(request,response); 

            return ; 

        } 

         

        String registerName = (String)request.getSession().getAttribute(registerID); 

         // 如果session设置的有限时间过期,则注册不成功,直接返回

        if(registerName
== null || registerName.equals("")){ 

            request.getRequestDispatcher("/index.jsp").forward(request,response); 

            return ; 

        } 

         

        request.setAttribute("registerName", registerName); 

        request.getRequestDispatcher("/registSuccess.jsp").forward(request,response); 

    } 

 

    public void doPost(HttpServletRequest
request, HttpServletResponse response) 

            throws ServletException,
IOException { 

        doGet(request, response); 

    } 


######################################################################
index.jsp

######################################################################
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 

<html> 

  <head> 

    <title>用户注册利用邮箱进行验证</title> 

  </head> 

  <body> 

  <br/> 

    <form action="${pageContext.request.contextPath
}/servlet/RegisterServlet" method="post"> 

        <font size="24" color="red">用户注册</font/><br/>

           邮箱:<input type="text" name="email" /><br/>

           昵称:<input type="text" name="userName" /><br/> 

        <input type="submit" value="submit" /><br/>
    </form> 

  </body> 

</html> 

######################################################################
registSuccess.jsp

######################################################################
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 

<!DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 

<html> 

  <head> 

    <title>注册成功</title>
  </head>  

  <body> 

         您好,${registerName
}  ,注册成功,正在跳转....<br/>     

  </body> 

</html> 

######################################################################
  sendMailSuccess.jsp
######################################################################

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>
  </head>  
  <body>

       请在10分钟之内登录邮箱,点击链接完成注册.<br>

  </body>

</html>

############################################################################################################################

1、如果出现上述错误,那么你要检查你的源邮箱中的SMTP/POP3服务是否开启,

##########################  Console  ##########################

DEBUG: setDebug: JavaMail version 1.3

DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]

DEBUG SMTP: useEhlo true, useAuth true

DEBUG SMTP: useEhlo true, useAuth true

DEBUG: SMTPTransport trying to connect to host "smtp.qq.com", port 25

DEBUG SMTP RCVD: 220 smtp.qq.com Esmtp QQ Mail Server

DEBUG: SMTPTransport connected to host "smtp.qq.com", port: 25

DEBUG SMTP SENT: EHLO O8NUWIZBJXNTYWH

DEBUG SMTP RCVD: 250-smtp.qq.com

250-PIPELINING

250-SIZE 52428800

250-AUTH LOGIN PLAIN

250-AUTH=LOGIN

250-MAILCOMPRESS

250 8BITMIME

DEBUG SMTP Found extension "PIPELINING", arg ""

DEBUG SMTP Found extension "SIZE", arg "52428800"

DEBUG SMTP Found extension "AUTH", arg "LOGIN PLAIN"

DEBUG SMTP Found extension "AUTH=LOGIN", arg ""

DEBUG SMTP Found extension "MAILCOMPRESS", arg ""

DEBUG SMTP Found extension "8BITMIME", arg ""

DEBUG SMTP: Attempt to authenticate

DEBUG SMTP SENT: AUTH LOGIN

DEBUG SMTP RCVD: 334 VXNlcm5hbWU6

DEBUG SMTP SENT: NTY5MjA0MjM3QHFxLmNvbQ==

DEBUG SMTP RCVD: 334 UGFzc3dvcmQ6

DEBUG SMTP SENT: MTk4ODEwMjgq

DEBUG SMTP RCVD: 454 Authentication failed, please open smtp flag first!

javax.mail.SendFailedException: Sending failed;

nested exception is:

    class javax.mail.AuthenticationFailedException

    at javax.mail.Transport.send0(Transport.java:218)

    at javax.mail.Transport.send(Transport.java:80)

    at control.RegisterServlet.doGet(RegisterServlet.java:65)

    

   ·····
 
##############################################################

下面是qq邮箱中的设置:





2、如果是刚刚注册的邮箱将会出错,因为刚刚注册的邮箱SMTP服务并没有打开,在qq邮箱中会有提示,注册14天之后才可以设置SMTP打开。






 


QQ邮箱的POP3与SMTP服务器是什么?

QQ邮箱 POP3 和 SMTP 服务器地址设置如下:
邮箱POP3服务器(端口110)SMTP服务器(端口25)
qq.compop.qq.comsmtp.qq.com
SMTP服务器需要身份验证。
 
如果是设置POP3和SMTP的SSL加密方式,则端口如下:
POP3服务器(端口995)
SMTP服务器(端口465或587)。

搜狐邮箱服务器: pop.sohu.com

                               smtp.sohu.com

 
网易邮箱服务器: pop.163.com

                               smtp.163.com

新浪邮箱服务器: pop.sina.com

                               smtp.sina.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: