Java,无法在Linux上发送邮件

时间:2018-07-29 19:38:05

标签: java linux email gmail

使用家用计算机,我可以通过Gmail发送电子邮件而不会出现错误,但是,当我尝试在Linux机器上运行相同的代码时,它会抛出:

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2182)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:726)
    at javax.mail.Service.connect(Service.java:388)
    at javax.mail.Service.connect(Service.java:246)
    at javax.mail.Service.connect(Service.java:195)
    at javax.mail.Transport.send0(Transport.java:254)
    at javax.mail.Transport.send(Transport.java:124)
    at io.paratek.updates.util.Mail.sendMail(Mail.java:34)
    at io.paratek.updates.MailTest.main(MailTest.java:8)

我的代码

public class Mail {

public static void sendMail(String subject, String contents, String to) {

    Properties props = System.getProperties();
    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.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("myemail", "mypasswd");
                }
            });

    try {

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(to));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setText(contents);
        Transport.send(message);

        System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
        mex.printStackTrace();
    }

}

}

我在两个系统上都使用Oracle JDK 181。 我能够在Linux机器上成功连接“ telnet smtp.gmail.com 465”

1 个答案:

答案 0 :(得分:0)

切换到TLS后可以使用

    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");
    props.put("mail.smtp.ssl.trust", "smtp.gmail.com");