发送电子邮件jsp Glassfish

时间:2015-08-13 10:21:28

标签: java jsp glassfish ejb javamail

我要做的是在特定时间内通过Gmail自动向客户发送电子邮件作为提醒。所以我在YouTube上找到了一个教程:https://www.youtube.com/watch?v=gy2eEZhLihk,我做了同样的事情,相同的代码,但我没有工作。

这是我的代码,我正在使用eclipse和Glassfish服务器。

  

Page1:MailDispatcherServlet

package com.hubberspot.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hubberspot.ejb.MailSenderBean;


/**
 * Servlet implementation class MailDispatcherServlet
 */
@WebServlet("/MailDispatcherServlet")
public class MailDispatcherServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */

@EJB
private MailSenderBean mailSender;

public MailDispatcherServlet() {
    super();
    // TODO Auto-generated constructor stub
}



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


    response.setContentType("text/html");
    String toEmail = request.getParameter("Email");
    String subject = request.getParameter("Subject");
    String message = request.getParameter("Message");

    // Properties ...

    String fromEmail = "majjane.ma@gmail.com";
    String username = "majjane.ma";
    String password = "majjane.ma20";



    try (PrintWriter out= response.getWriter()){

        // Call to mail sender bean

        mailSender.sendEmail(fromEmail, username, password, toEmail, subject, message);


        //---------------------------

    out.println("<!Doctype html>");
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Mail Status</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Mail Status !!!</h1>");
    out.println("<b>Mail sent successfully</b><br>");
    out.println("Click <a href='emailClient.jsp'>here</a> to go back !!!");
    out.println("</body>");
    out.println("</html>");

    }
}

/**
 * @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);
}

protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    /*response.setContentType("text/html");
    String toEmail = request.getParameter("Email");
    String subject = request.getParameter("Subject");
    String message = request.getParameter("Message");

    // Properties ...

    String fromEmail = "majjane.ma@gmail.com";
    String username = "majjane.ma";
    String password = "Majjane.Ma2";



    try (PrintWriter out= response.getWriter()){

        // Call to mail sender bean




        //---------------------------

    out.println("<!Doctype html>");
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Mail Status</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Mail Status !!!</h1>");
    out.println("<b>Mail sent successfully</b><br>");
    out.println("Click <a href='emailClient.jsp'>here</a> to go back !!!");
    out.println("/body");
    out.println("</html>");

    }
    */

}
}
  

Page2:MailSenderBean

package com.hubberspot.ejb;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


@Stateless

public class MailSenderBean {


public void sendEmail(String fromEmail,String username, String password, String toEmail, String subject,String message) {

    try {
    Properties props = System.getProperties();
    props.put("mail.smtp.host","smtp.gmail.com");
    props.put("mail.smtp.auth","true");
    props.put("mail.smtp.port","465");
    props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.port","465");
    props.put("mail.smtp.socketFactory.fallback","false");



    Session mailSession = Session.getDefaultInstance(props, null);
    mailSession.setDebug(true);

    Message mailMessage = new MimeMessage(mailSession);


        mailMessage.setFrom(new InternetAddress(fromEmail));
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        mailMessage.setContent(message, "text/html");
        mailMessage.setSubject(subject);


        Transport transport = mailSession.getTransport("smtp");
        transport.connect("smtp.gmail.com",username ,password);

        transport.sendMessage(mailMessage, mailMessage.getAllRecipients());



    } catch (Exception ex) {

        Logger.getLogger(MailSenderBean.class.getName()).log(Level.SEVERE, null, ex);

    }


}

}
  

第3页:emailClient

This page has a form where I enter message, subject and the client adress. These parameters will be sent to the action page "MailDispatcherServlet", the method is Get.
  

这是我的控制台上显示的内容:

  2015-08-13T10:08:11.264+0100|Infos: DEBUG: setDebug: JavaMail version 1.5.0
  2015-08-13T10:08:11.264+0100|Infos: DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
  2015-08-13T10:08:11.264+0100|Infos: DEBUG SMTP: useEhlo true, useAuth true
  2015-08-13T10:08:11.264+0100|Infos: DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL false
  2015-08-13T10:08:13.441+0100|Grave: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
      javax.net.ssl.SSLHandshakeException:       sun.security.validator.ValidatorException: PKIX path building failed:       sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1963)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:345)
at javax.mail.Service.connect(Service.java:226)
at com.hubberspot.ejb.MailSenderBean.sendEmail(MailSenderBean.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy222.sendEmail(Unknown Source)
at com.hubberspot.ejb.__EJB31_Generated__MailSenderBean__Intf____Bean__.sendEmail(Unknown Source)
at com.hubberspot.servlet.MailDispatcherServlet.doGet(MailDispatcherServlet.java:61)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
  Caused by: javax.net.ssl.SSLHandshakeException:       sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1884)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:333)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:208)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
... 67 more
  Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
... 78 more
  Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
... 84 more

如果您需要任何其他详细信息,请与我们联系。

谢谢你,
 苯并

1 个答案:

答案 0 :(得分:0)

 Transport transport = mailSession.getTransport("smtps");// change smtp to smtps

并禁用您的PC防病毒和防火墙,然后尝试

并启用“访问不太安全的应用”

https://www.google.com/settings/security/lesssecureapps

然后就能成功发送邮件。