1

我无法执行可公开用于通过 Gmail 发送电子邮件的代码。我认为这可能是网络问题,因为我正在工作,尽管我可以通过cmd提示ping Gmail ping smtp.gmail.com:.

这是我正在使用的代码(来自此页面):

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;


class tester {
    public static void main(String args[]) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.stmp.user", "username of the sender");          
        //If you want you use TLS 
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.password", "password of the sender");
        // If you want to use SSL
        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 Authenticator() {
            @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    String username = "username";
                    String password = "password";
                    return new PasswordAuthentication("username","password"); 
                }
            });
        String to = "me@gmail.com";
        String from = "from@gmail.com";
        String subject = "Testing...";
        MimeMessage msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(from));
            msg.setRecipient(MimeMessage.RecipientType.TO, new    InternetAddress(to));
            msg.setSubject(subject);
            msg.setText("JAVA is the BEST");
            Transport transport = session.getTransport("smtp");
            transport.send(msg);
            System.out.println("E-mail sent !");
        } catch(Exception exc) {
            System.out.println(exc);
        }
    }
}

我已将用户名和密码字段更改为正确。有哪些事情可能会导致这种情况?我为此使用了自己的代码和许多其他公开可用的代码,但我得到了同样的错误。我也尝试通过端口 587 运行并收到相同的错误。

这是错误:

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is: java.net.ConnectException: Connection refused: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
    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 GoogleMail.sendMail(GoogleMail.java:45)
4

1 回答 1

0

我在提示符中使用了telnet smtp.gmail.com 465andtelnet smtp.gmail.com 587命令,cmd两者都无法连接。我假设它与我连接的网络相关联。我无法提供除此之外的任何信息,如果我发现更多信息,我会更新。

于 2013-06-12T15:42:33.507 回答