Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javax.mail.AuthenticationFailedException:535身份验证失败(#5.7.1)_Java_Jsp_Servlets_Jakarta Mail - Fatal编程技术网

javax.mail.AuthenticationFailedException:535身份验证失败(#5.7.1)

javax.mail.AuthenticationFailedException:535身份验证失败(#5.7.1),java,jsp,servlets,jakarta-mail,Java,Jsp,Servlets,Jakarta Mail,我正在使用javamail api制作一个自动发送电子邮件的java项目。当我使用smtp.gmail.com主机发送此邮件时,它可以正常工作。但当我使用自己的主机服务器mail.sitename.com时…它显示异常..我的用户名和密码是正确的。请任何人帮我解决这个问题。。。 例外情况是:- javax.mail.AuthenticationFailedException: 535 authentication failed (#5.7.1) at com.sun.mail.

我正在使用javamail api制作一个自动发送电子邮件的java项目。当我使用smtp.gmail.com主机发送此邮件时,它可以正常工作。但当我使用自己的主机服务器mail.sitename.com时…它显示异常..我的用户名和密码是正确的。请任何人帮我解决这个问题。。。 例外情况是:-

    javax.mail.AuthenticationFailedException: 535 authentication failed (#5.7.1)

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at com.zenga.servlet.MailNotification.sendMail(MailNotification.java:130)
    at com.zenga.servlet.MailNotification.doPost(MailNotification.java:45)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
代码:---

a) 我正在使用DAO模式获取数据,以用于to(电子邮件id)目的 b) 一个jsp文件,以开始和限制获取与我将要发送的电子邮件没有任何连接。。 c) Servlet文件如下所示

package com.zenga.servlet;

import java.io.*;
import java.security.GeneralSecurityException;
import java.util.*;
import com.sun.mail.util.MailSSLSocketFactory;
import com.zenga.dao.DaoFactory;
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 javax.mail.*;
import javax.mail.internet.*;

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

    @SuppressWarnings("unchecked")
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        HashMap<String, String>list =   new HashMap<String, String>();
        Set<?> set      =   null;
        Iterator<?> itr =   null;
        int start   =   0;
        int limit   =   0;
        Map.Entry<String, String> me = null;
        try {
            DaoFactory dao  =   DaoFactory.getDao();
            start   =   Integer.parseInt(request.getParameter("start"));
            limit   =   Integer.parseInt(request.getParameter("end"));
            list    =   dao.insertLimit(start,limit);
            set     =   list.entrySet();
            itr     =   set.iterator();

            while(itr.hasNext()) {
                me  =   (Map.Entry<String, String>)itr.next();
                sendMail(me.getKey(),me.getValue(),request,response);
            }
        } catch (Exception e) {

        }

    }

    private void sendMail(String toUsername, String to,HttpServletRequest request,HttpServletResponse response) throws IOException, GeneralSecurityException {

       final String from        =   "xyz@sitename.com";
       final String subject     =   "a subject";
       final String password    =   "password";
       final String host        =   "mail.sitename.com";
         String msg         =    getMessage(toUsername);

            //Set the host SMTP address

                  /*MailSSLSocketFactory socketFactory= new MailSSLSocketFactory();
            socketFactory.setTrustAllHosts(true);

            Properties properties=System.getProperties();
            properties.put("mail.smtp.host", host);
            properties.put("mail.smtp.user", from);
            properties.put("mail.smtp.password", password);
            //properties.put("mail.smtp.starttls.enable","true");
            properties.put("mail.smtp.ssl.socketFactory", socketFactory);
             properties.put("mail.smtp.EnableSSL.enable","true");


        //  properties.put("mail.smtp.ssl.enable","false");
            properties.put("mail.smtp.ssl.trust",host);
            properties.put("mail.protocol.ssl.trust", host);
            properties.put("mail.smtp.socketFactory.port", "587");
                    properties.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
            properties.put("mail.smtp.port", "587");
            properties.put("mail.smtp.auth", "true");
            */ 

            Properties properties=System.getProperties();
            properties.put("mail.smtp.host",host);
            properties.put("mail.smtp.user",from);
            properties.put("mail.smtp.password",password);
            properties.put("mail.smtp.port","587");
            properties.put("mail.smtp.auth","true");
        //  properties.put("mail.smtp.starttls.enable","true");
                properties.put("mail.smtp.ssl.enable","false");
                properties.put("mail.smtp.starttls.enable","false");

            Authenticator auth = new Authenticator(){
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from,password);
                }
            };
            Session session=Session.getDefaultInstance(properties,auth);
            response.setContentType("text/html");
            try{
                // create a message

                MimeMessage message=new MimeMessage(session);

                // set the from and to address
              //  InternetAddress addressFrom = new InternetAddress(from);
                message.setFrom(new InternetAddress(from));
                //InternetAddress addressTo   = new InternetAddress(to);
                message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));

                // Setting the Subject and Content Type
                message.setSubject(subject);

                // create and fill the first message part
                MimeBodyPart msgBodypart = new MimeBodyPart();

                msgBodypart.setText(msg,"ascii","hmtl");


                // create the Multipart and add its parts to it
                Multipart multipart=new MimeMultipart();
                multipart.addBodyPart(msgBodypart);
                // add the Multipart to the message
                message.setContent(multipart);
                // set the Date: header
                message.setSentDate(new Date());

                        Transport.send(message);
                        success++;


            }
            catch(MessagingException me)
            { 
                failed++;
                me.printStackTrace();
            }
     }



    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
}
package com.zenga.servlet;
导入java.io.*;
导入java.security.GeneralSecurityException;
导入java.util.*;
导入com.sun.mail.util.mailssocketFactory;
进口com.zenga.dao.dao工厂;
导入javax.servlet.ServletException;
导入javax.servlet.annotation.WebServlet;
导入javax.servlet.http.HttpServlet;
导入javax.servlet.http.HttpServletRequest;
导入javax.servlet.http.HttpServletResponse;
导入javax.mail.*;
导入javax.mail.internet.*;
/**
*Servlet实现类send
*/
@WebServlet(“/send”)
公共类MailNotification扩展了HttpServlet{
私有静态最终长serialVersionUID=1L;
@抑制警告(“未选中”)
受保护的void doPost(HttpServletRequest请求、HttpServletResponse响应)引发ServletException、IOException{
//TODO自动生成的方法存根
HashMaplist=新的HashMap();
Set=null;
迭代器itr=null;
int start=0;
整数极限=0;
Map.Entry me=null;
试一试{
DaoFactory dao=DaoFactory.getDao();
start=Integer.parseInt(request.getParameter(“start”);
limit=Integer.parseInt(request.getParameter(“end”);
list=dao.insertLimit(开始,限制);
set=list.entrySet();
itr=set.iterator();
while(itr.hasNext()){
me=(Map.Entry)itr.next();
sendMail(me.getKey()、me.getValue()、请求、响应);
}
}捕获(例外e){
}
}
私有void sendMail(String-toUsername、String-to、HttpServletRequest请求、HttpServletResponse响应)引发IOException、GeneralSecurityException{
最后一个字符串from=”xyz@sitename.com";
最后一个字符串subject=“a subject”;
最终字符串password=“password”;
最后一个字符串host=“mail.sitename.com”;
字符串msg=getMessage(toUsername);
//设置主机SMTP地址
/*MailSSLSocketFactory socketFactory=新的MailSSLSocketFactory();
setTrustAllHosts(true);
Properties=System.getProperties();
properties.put(“mail.smtp.host”,host);
properties.put(“mail.smtp.user”,from);
properties.put(“mail.smtp.password”,password);
//properties.put(“mail.smtp.starttls.enable”、“true”);
properties.put(“mail.smtp.ssl.socketFactory”,socketFactory);
properties.put(“mail.smtp.EnableSSL.enable”,“true”);
//properties.put(“mail.smtp.ssl.enable”、“false”);
properties.put(“mail.smtp.ssl.trust”,主机);
properties.put(“mail.protocol.ssl.trust”,主机);
properties.put(“mail.smtp.socketFactory.port”,“587”);
properties.put(“mail.smtp.socketFactory.class”,
“javax.net.ssl.SSLSocketFactory”);
properties.put(“mail.smtp.port”,“587”);
properties.put(“mail.smtp.auth”、“true”);
*/ 
Properties=System.getProperties();
properties.put(“mail.smtp.host”,host);
properties.put(“mail.smtp.user”,from);
properties.put(“mail.smtp.password”,password);
properties.put(“mail.smtp.port”,“587”);
properties.put(“mail.smtp.auth”、“true”);
//properties.put(“mail.smtp.starttls.enable”、“true”);
properties.put(“mail.smtp.ssl.enable”、“false”);
properties.put(“mail.smtp.starttls.enable”、“false”);
Authenticator auth=新的验证器(){
公共密码身份验证getPasswordAuthentication(){
返回新的PasswordAuthentication(from,password);
}
};
Session Session=Session.getDefaultInstance(属性,身份验证);
response.setContentType(“text/html”);
试一试{
//创建消息
MimeMessage message=新MimeMessage(会话);
//设置发件人和收件人地址
//InternetAddress addressFrom=新的InternetAddress(from);
message.setFrom(新的InternetAddress(from));
//InternetAddress addressTo=新的InternetAddress(to);
message.addRecipient(message.RecipientType.TO,新的Internet地址(TO));
//设置主题和内容类型
message.setSubject(主题);
//创建并填充第一个消息部分
MimeBodyPart msgBodypart=新的MimeBodyPart();
msgBodypart.setText(msg,“ascii”,“hmtl”);
//创建多部分并将其部分添加到其中
Multipart Multipart=新的MimeMultipart();
多部分addBodyPart(msgBodypart);
//将多部分添加到消息中
message.setContent(多部分);
//设置日期:页眉
message.setSentDate(新日期());
传输。发送(消息);
成功++;
}
捕获(消息例外我)
{ 
失败++;
me.printStackTrace();
}
}
/**
*@参见HttpServlet#doPost(HttpServletRequest,HttpServletRe
==================== Properties Section ====================
! Default Properties for the Email section of the project - others omitted

! The email provider may or may not require authentication - make sure to make the appropriate choices on the client
EmailSender = aUser@gmail.com
EmailPassword = unEncriptedPassword
EmailRecipients = me@gmail.com,she@gmail.com,you@yahoo.com,andAnyBodyElse@aol.com
EmailHost = smtp.gmail.com
EmailPort = 587
EmailAuthenticationRequired = true

==================== Code Section ====================
public class Email {

   public static void sendMail(String subject, String messageBody, String fileName) throws MessagingException {

      DDTSettings settings = DDTSettings.Settings();
      final String sender = settings.emailSender();
      final String password = settings.emailPassword();
      String[] recipients = settings.emailRecipients().split(",");
      String host = settings.emailHost();
      String port = settings.emailPort();
      boolean emailAuthenticationRequired = settings.emailAuthenticationRequired();
      String trueOrFalse = emailAuthenticationRequired ? "true" : "false";
      Properties properties = System.getProperties();
      Session session;

      // Use system properties and add some related to email protocol
      Properties props = System.getProperties();

      // Setup mail server
      props.setProperty("mail.smtp.host", host);
      props.setProperty("mail.smtp.port", port);
      props.setProperty("mail.smtp.ssl.enable", "false");
      props.setProperty("java.net.preferIPv4Stack","true");
      props.setProperty("mail.smtp.starttls.enable", trueOrFalse);
      props.setProperty("mail.smtp.auth", trueOrFalse);

      // Create a session with or without authentication object as indicated in the settings.
       if (emailAuthenticationRequired) {
           Authenticator auth = new Authenticator() {
               protected PasswordAuthentication  getPasswordAuthentication() {
                   return new PasswordAuthentication(sender, password);
               }
           };
           session = Session.getDefaultInstance(props, auth);
       }
       else {
           props.setProperty("mail.smtp.user", sender); // Needed if not authenticating
           props.setProperty("mail.smtp.password", password); // Needed if not authenticatin 
           session = Session.getDefaultInstance(props);
       }

       // Setup the message in two parts, body and attachment then send it
      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(sender));
         //message.setReplyTo({new InternetAddress(sender)});

         // Set recipients
         for (int i = 0; i<recipients.length; i++) {
            message.addRecipient(Message.RecipientType.TO,
                  new InternetAddress(recipients[i]));
         }

         // Set Subject: header field
         message.setSubject(subject);

         // Create the message part
         BodyPart messageBodyPart = new MimeBodyPart();

         // Set the body of the message as html content
         messageBodyPart.setContent(messageBody, "text/html");

         // Create a multipart message
         Multipart multipart = new MimeMultipart();

         // Set text message part
         multipart.addBodyPart(messageBodyPart);

         // Part two is attachment
         messageBodyPart = new MimeBodyPart();
         DataSource source = new FileDataSource(fileName);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(source.getName());  
         multipart.addBodyPart(messageBodyPart);

         // Place the entire kit & caboodle in the message
         message.setContent(multipart );

         // Send message
         Transport.send(message);
      }
      catch (MessagingException e) {
         e.printStackTrace();
      }

   }
}