1

我正在学习如何使用 javamail API 发送电子邮件,我已经创建了使用 SMTP 服务器发送简单电子邮件的必要属性和说明,并且我正在使用以下代码:

     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 getpPasswordAuthentication(){
    return new  PasswordAuthentication("myemailadresse@gmail.com", "password");
    }


    });
    try{
        Message message=new MimeMessage(session);
        message.setFrom(new InternetAddress("myemail"));    
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recepientemailadresse"));
        message.setSubject("the java mail test");
        message.setText("Guess what brother the java mail is working correctly");
        Transport.send(message);
         JOptionPane.showMessageDialog(rootPane, "message sent");
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(rootPane, e);
         e.printStackTrace();
    }

我在运行时发生了一个异常,提到:

    javax.mail.AuthenticationFailedException: failed to connect, no password specified?
at javax.mail.Service.connect(Service.java:329)
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 transfer.Maitest.jButton1ActionPerformed(Maitest.java:96)
at transfer.Maitest.access$000(Maitest.java:20)
at transfer.Maitest$1.actionPerformed(Maitest.java:45)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)

你能告诉我我错过了什么吗?

4

2 回答 2

1

首先,阅读这个关于常见错误的 JavaMail FAQ 条目。更正它们后,请阅读此JavaMail FAQ 条目,该条目告诉您如何连接到 Gmail。如果它仍然不起作用,这个关于调试的 JavaMail FAQ 条目会有所帮助。

于 2012-10-11T20:45:41.710 回答
0

如果您的电子邮件服务器不需要身份验证并且您不想提供密码(例如,测试环境),请尝试以下操作:

props.put("mail.smtp.auth", "false");
于 2013-08-21T11:48:23.213 回答