我正在尝试用java编写一个发送电子邮件的应用程序,我在youtube上找到了一个教程并尝试遵循它。但是它仍然对我不起作用,这是我得到的错误
Exception in thread "main" javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25, response: 421
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1949)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:295)
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 libraryFineList.ParseRecords.main(ParseRecords.java:90)
我不知道出了什么问题,我在谷歌上找到的任何东西都没有帮助,
这是代码
public static void main(String[] args) throws IOException, MessagingException {
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 getPasswordAuthentication(){
return new PasswordAuthentication("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2d7d1c7d0e2c5cfc3cbce8cc1cdcf" rel="noreferrer noopener nofollow">[email protected]</a>", "pass");
}
}
);
try{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2c7c1d7c0f2d5dfd3dbde9cd1dddf" rel="noreferrer noopener nofollow">[email protected]</a>"));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ae3f9f2fbe8f4ffeee9f1fbe3fbdafdf7fbf3f6b4f9f5f7" rel="noreferrer noopener nofollow">[email protected]</a>", "Mr. User"));
message.setSubject("Your Example.com account has been activated");
message.setText("Worked");
Transport.send(message);
}catch(Exception e){
e.printStackTrace();
}
最佳答案
您遵循的教程充满了错误。首先修复这些common mistakes 。然后按照这些instructions for connecting to Gmail 。如果您仍然遇到问题,您可以在 JavaMail FAQ 中找到更多帮助。 。还有很多sample programs可用。
关于JavaMail 无法发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24543108/