Connection timed out JavaMail API GMail

823
28 декабря 2016, 03:33

Использую JavaMail API для отправки почты.

Делаю вот так:

public void sendMail() {
        try {
            String SMTP_AUTH_USER = "test@gmail.com";
            String SMTP_AUTH_PWD = "test123456";
            Properties props = new Properties();
            /*props.put("mail.transport.protocol", "smtps");
            props.put("mail.smtp.ssl.enable", "true");*/
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.auth", "true");
            props.put("mail.debug", "true");
            props.put("mail.smtp.port", 587);
            props.put("mail.smtp.socketFactory.port", 587);
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
            Session session = Session.getDefaultInstance(props);
            session.setDebug(true);
            Transport transport = session.getTransport();
            transport.connect("smtp.gmail.com", 547, SMTP_AUTH_USER, SMTP_AUTH_PWD);
            MimeMessage message = new MimeMessage(session);
            message.setSubject("Test Mail from Java Program");
            message.setText("You can send mail from Java program by using mail API, but you need" +
                    "couple of more JAR files e.g. smtp.jar and activation.jar");
            InternetAddress address = new InternetAddress("test@gmail.com");
            message.addRecipient(Message.RecipientType.TO, address);
            message.setSentDate(new Date());
            transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
    }

Получаю вот такое:

DEBUG: JavaMail version 1.5.6
DEBUG: URL jar:file:/E:/IDEA/YourLinks%20v2/out/artifacts/YourLinks_war_exploded/WEB-INF/lib/smtp-1.5.6.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: jar:file:/E:/IDEA/YourLinks%20v2/out/artifacts/YourLinks_war_exploded/WEB-INF/lib/smtp-1.5.6.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: URL jar:file:/E:/IDEA/YourLinks%20v2/out/artifacts/YourLinks_war_exploded/WEB-INF/lib/smtp-1.5.6.jar!/META-INF/javamail.address.map
DEBUG: successfully loaded resource: jar:file:/E:/IDEA/YourLinks%20v2/out/artifacts/YourLinks_war_exploded/WEB-INF/lib/smtp-1.5.6.jar!/META-INF/javamail.address.map
DEBUG: setDebug: JavaMail version 1.5.6
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 547, isSSL false
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 547; timeout -1;
  nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2118)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:712)
    at javax.mail.Service.connect(Service.java:366)
    at ru.tsyklop.utils.SendMailTLS.sendMail(SendMailTLS.java:73)
    at ru.tsyklop.yourlinks.Controller.doPost(Controller.java:26)
    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:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    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)
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:331)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2084)
    ... 28 more
Answer 1

Вот здесь есть рабочий пример отправки почты при помощи JavaMail API.

С TLS-шифрованием:

public class SendMailTLS {
    public static void main(String[] args) {
        final String username = "username@gmail.com";
        final String password = "password";
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
        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("from-email@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("to-email@gmail.com"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");
            Transport.send(message);
            System.out.println("Done");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

С SSL-шифрованием:

public class SendMailSSL {
    public static void main(String[] args) {
        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("from@no-spam.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("to@no-spam.com"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler," +
                    "\n\n No spam to my email, please!");
            Transport.send(message);
            System.out.println("Done");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
READ ALSO
Прикладное программирование C++/Java [требует правки]

Прикладное программирование C++/Java [требует правки]

В интернете довольно много обсуждений по этому поводуИнтересует мнение исходя из нынешнего времени 2016/2017

429
Поле ввода с маской ММ/ГГ

Поле ввода с маской ММ/ГГ

Прошу покритиковать код с примерами чем бы вы что заменилиДан кусок кода и он касается только поля "срок действия"

431
Назначение пакетов rt.jar

Назначение пакетов rt.jar

Некоторое время назад был задан вопрос о разнице классов из пакетов orgxml и jdk

444
Вывод на экран треугольника

Вывод на экран треугольника

Написал код для вывода треугольника:

512