3

我当前的代码是(我在实际代码中使用正确的用户名和密码):-

            public class MailTry {

                public static void main(String[] args) {

                    final String username = "user@gmail.com";
                    final String password = "pass";

                    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(username));
                        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);
                    }
                }
            }

我在上面的代码中遇到了以下异常:-

            Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
              nested exception is:
                java.net.ConnectException: Connection timed out: connect
                at MailTry.main(MailTry.java:63)
            Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
              nested exception is:
                java.net.ConnectException: Connection timed out: connect
                at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
                ....
                ....

对于 http 客户端,我使用以下 java 代码使用代理,它运行良好:

             String proxyHost = "172.22.6.26";
             int proxyPort = 80;
             Properties systemSettings = System.getProperties();
             systemSettings.put("http.proxyPort",proxyPort);
             systemSettings.put("http.proxyHost",proxyHost);

我不确定确切的问题是什么,但我认为它应该与代理或防火墙有关。我已经尝试了几个代码在 smtp 客户端中使用代理,但它们都没有正常工作。

4

0 回答 0