使用java从代理服务器后面使用gmail发送邮件

时间:2013-06-13 11:18:36

标签: java email proxy smtp gmail

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

            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客户端中使用代理,但它们都没有正常工作。

0 个答案:

没有答案