Java Mail 无法验证 openshift 服务器中的 smtp 设置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19311823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:59:48  来源:igfitidea点击:

Java Mail fails to authenticate smtp setting in openshift server

javaemailjavamail

提问by Maclean Pinto

I have written the following bean to authenticate my mail.

我编写了以下 bean 来验证我的邮件。

public class Mail_Authenticator {

   public Session Get_Auth() {
        // sets SMTP server properties
        ResourceBundle rs_mail = ResourceBundle.getBundle("mail");
        final String userName=rs_mail.getString("username");
        final String password=rs_mail.getString("password");
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.user", userName);   

        //creates a new session with an authenticator
        Authenticator auth = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        };
        return (Session.getInstance(properties, auth));

    }
}

The problem is with the smtp settings, when I run the application on my local server it works fine. But when I run application on openshift server exception is caused at

问题出在 smtp 设置上,当我在本地服务器上运行应用程序时,它运行良好。但是当我在 openshift 服务器上运行应用程序时,异常是在

Transport.send(msg);

Could any one please point out the problem, in the above settings and why are they working in my local machine?

任何人都可以指出问题,在上述设置中,为什么它们在我的本地机器上工作?

Following is the exception that i get

以下是我得到的例外

javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbsWq 534-5.7.14 JJjb_c-FzrtUAccdDqOCMtsPAOL1AwIDSCtheitroadeBRoI5X-avznrYbparV84O_zkAvrHXMB9 534-5.7.14 T0Zj8zXP1g1woaWHnTzJQ3vWFn3lwTNl9Kn8Ma9-d9FPD_xB-bMBSh5FEPdaMqID4WljXW 534-5.7.14 v67IfQzXHolKlY48pEiZF-cpGc6CEgknkET1ciEQf51vQuETuMrrzeC7EDcM7s89Njtm5e 534-5.7.14 crMNRLw> Please log in via your web browser and then try again. 534-5.7.14 Learn more at https://support.google.com/mail/bin/answer.py?answer=787 534 5.7.14 54 e7sm180653184qag.7 - gsmtp

at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:823)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:756)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:673)
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 Servlet.Mail.sendEmail(Mail.java:72)
at Servlet.Mail.doGet(Mail.java:206)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
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:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)

采纳答案by Snake Eye

I had a same problem. Try logging to gmail account from a browser . Gmail blocks the authentication request if he thinks is a illegal access(maybe from a different geography). You might see a message or notification. Follow the instruction in the notification or message and then you can unblock the authentication requests. Your authentication will work.

我有同样的问题。尝试从浏览器登录到 gmail 帐户。如果 Gmail 认为是非法访问(可能来自不同的地理位置),则会阻止身份验证请求。您可能会看到一条消息或通知。按照通知或消息中的说明操作,然后您可以取消阻止身份验证请求。您的身份验证将起作用。

I had used following code :

我使用了以下代码:

public void sendMail(String mailId,String outputFile) {

    final String username = "[email protected]";
    final String password = "MyPassowrd";

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username,password);
            }
        });

    try {

        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(mailId));
        message.setSubject("MySubject");

        MimeBodyPart messageBodyPart =  new MimeBodyPart();
        messageBodyPart.setText("This is the mail content");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = 
          new FileDataSource(outputFile);
        messageBodyPart.setDataHandler(
          new DataHandler(source));
        messageBodyPart.setFileName("MyFile.pdf");
        multipart.addBodyPart(messageBodyPart);

        // Put parts in message
        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

回答by lquitadamo

Static method of class Transport is wrong because doesn't use the settings of Session object. Use example Gmail with JavaMail

类 Transport 的静态方法是错误的,因为不使用 Session 对象的设置。将示例Gmail 与 JavaMail 结合使用

The code is like this:

代码是这样的:

String host = "smtp.gmail.com";
String username = "user";
String password = "passwd";
Properties props = new Properties();
props.put("mail.smtps.auth", "true");
// ...
MimeMessage msg = new MimeMessage(session);
// set the message content here
Transport t = session.getTransport("smtps");
try {
t.connect(host, username, password);
t.sendMessage(msg, msg.getAllRecipients());
} finally {
t.close();
}

回答by Jhanvi

Try this:

尝试这个:

    Properties props = new Properties();
    props.put("mail.smtp.user", username);
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "25");
    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.EnableSSL.enable", "true");
    props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.setProperty("mail.smtp.socketFactory.fallbac k", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("sENDER_EMAIL"));
        message.setSubject("SUBJECT_OF_MAIL");
        message.setText("MAIL_TEXT);

        Transport.send(message);

        System.out.println("Done");

    } catch (Exception e) {


    }