我无法使用以下代码发送电子邮件。我的库中有所有必需的罐子。我在mysql工作台上连接了一个数据库,我从表单动作中选择数据=" EmailListServlet"和来自数据库的用户详细信息。即使我能够在netbeans的输出窗口中接收输出,我收到一个异常消息,它位于catch块中。
EmailListServlet
@WebServlet(name = "EmailListServlet", urlPatterns = {"/EmailListServlet"})
public class EmailListServlet extends HttpServlet {
@EJB
private EmailSenderBean sendMail;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession(true);
session.setMaxInactiveInterval(-1);
String url ="";
EntityManager em = DBUtil.getEmFactory().createEntityManager();
User user= (User) session.getAttribute("theUser");
String name = request.getParameter("Name");
System.out.println("Name is"+name);
String fromEmail = request.getParameter("User_Id");
System.out.println("Sender Email is"+fromEmail);
String toEmail = request.getParameter("Friend_Id");
System.out.println("To Email is"+toEmail);
String message = request.getParameter("Message");
System.out.println("Message is"+message);
fromEmail = "'"+fromEmail+"'";
String userPwd = user.getPassword();
System.out.println("Password is" +userPwd);
try{
sendMail.SendEmail(name, fromEmail, userPwd, toEmail, message);
url="/confirmr.jsp";
}
catch(Exception e){
System.out.println("This is an Exception");
}
em.close();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
EmailSenderBean
@Stateless
public class EmailSenderBean {
public void SendEmail(String name, String fromEmail, String userPwd, String toEmail, String message ){
Properties props = System.getProperties();
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.auth", "true");
//props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketDactory.class", "javax.net.ssl.SSLSocketFactory");
//props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);
Message mailMessage = new MimeMessage(session);
try {
mailMessage.setFrom(new InternetAddress(fromEmail));
mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
mailMessage.setContent(message, "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("localhost", fromEmail, userPwd);
transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
}
catch (MessagingException ex) {
Logger.getLogger(EmailSenderBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
[EmailListServlet] in context with path [/Ojas_App] threw exception
java.lang.NullPointerException
at org.uncc.nbad.servlet.EmailListServlet.doPost(EmailListServlet.java:83)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2503)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2492)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745).
这指向sendMail.SendEmail(name,fromEmail,userPwd,toEmail,message);
答案 0 :(得分:0)
最后2天后,我可以运行此代码。我的更新代码在
下面共享EmailSenderBean.java
public class EmailSenderBean {
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
public void sendEmail(String name, String fromEmail, String toEmail, String subject, String message) {
Properties props = System.getProperties();
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
String [] toEmails = {toEmail};
String emailSubject = subject;
String emailBody = message;
Session session = Session.getDefaultInstance(props, null);
Message mailMessage = new MimeMessage(session);
try {
String fromUser = "youremailid@gmail.com";
String fromUserEmailPassword = "yourpassword";
if(fromEmail!=null && !fromEmail.trim().equals("")){
mailMessage.setFrom(new InternetAddress(fromEmail));
}
else{
mailMessage.setFrom(new InternetAddress(fromUser));
}
for (String toEmail1 : toEmails) {
mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail1));
}
mailMessage.setSubject(emailSubject);
mailMessage.setContent(emailBody, "text/html");
String emailHost = "smtp.gmail.com";
Transport transport = session.getTransport("smtp");
transport.connect(emailHost, fromUser, fromUserEmailPassword);
transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
transport.close();
}
catch(AddressException ex){
ex.printStackTrace();
Logger.getLogger(EmailSenderBean.class.getName()).log(Level.SEVERE, null, ex);
}
catch (MessagingException ex) {
ex.printStackTrace();
Logger.getLogger(EmailSenderBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
EmailListServlet.java
@WebServlet(name = "EmailListServlet", urlPatterns = {"/EmailListServlet"})
public class EmailListServlet extends HttpServlet {
public EmailSenderBean sendMail;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String url="";
response.setContentType("text/html;charset=UTF-8");
EntityManager em = DBUtil.getEmFactory().createEntityManager();
String action = request.getParameter("action");
String name = request.getParameter("Name");
String fromEmail = request.getParameter("User_Id");
String toEmail = request.getParameter("Friend_Id");
String message = request.getParameter("Message");
sendMail = new EmailSenderBean();
String subject ="";
if(action.equals("contact")){
subject = "Contact made via ORNSurveys";
message = name+" wants to contact you via ORN SURVEYS"+message;
sendMail.sendEmail(name, null, toEmail, subject, message);
url = "/confirmc.jsp";
}else if(action.equals("recommend")){
subject = "Recommendation to join ORNSurveys";
message = name+" wants to recommend you to join ORN SURVEYS"+message;
sendMail.sendEmail(name, fromEmail, toEmail, subject, message);
url = "/confirmr.jsp";
}
em.close();
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
}
}