无法使用Apache Commons Email通过Gmail发送电子邮件。问题是什么?
Email email = new SimpleEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(587);
email.setTLS(true);
email.setAuthenticator(new DefaultAuthenticator("mymail@gmail.com", "mypassword"));
email.setFrom("mymail@gmail.com");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("sendmail@gmail.com");
email.send();
错误:
Exception in thread "main" org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:587
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1242)
at org.apache.commons.mail.Email.send(Email.java:1267)
at MailService.sendSimpleMail(MailService.java:51)
at MailService.main(MailService.java:17)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
at javax.mail.Service.connect(Service.java:310)
at javax.mail.Service.connect(Service.java:169)
at javax.mail.Service.connect(Service.java:118)
at javax.mail.Transport.send0(Transport.java:188)
at javax.mail.Transport.send(Transport.java:118)
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1232)
... 3 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
... 10 more
答案 0 :(得分:3)
有什么问题?
Could not connect to SMTP host
(直接从你似乎忽略的异常输出中复制。)
答案 1 :(得分:1)
请设置email.setDebug(true); 使用此命令,您可以知道您的确切问题是什么 也许你的用户名和密码错误
答案 2 :(得分:-1)
如果您使用的是常规Gmail帐户或Google Apps电子邮件帐户,则Gmail可能会阻止当前域。请确保您具有从其他应用程序发送邮件的足够权限。