让JavaMail API工作

时间:2015-03-19 15:56:05

标签: java api javamail

我正在开发一个使用JavaMail API发送电子邮件的应用程序,但我不断收到错误。我正在使用Eclipse对其进行编码,而我正在使用gmail发送它。我出于显而易见的原因取出了我的真实密码,因此如果你需要进行实验,你可能需要用自己的密码替换它。既然我已经修复了一些东西,感谢你们,我想我得到了一个超时错误,因为它需要很长时间才能显示错误,但除此之外,我还没有最模糊的线索。提前感谢您的任何帮助或建议。

代码:

package com.brighamcampbell.sunrisegundersonmail;

import java.io.UnsupportedEncodingException;
import java.util.Properties;  

import javax.mail.*;  
import javax.mail.internet.*;  

public class Mail {  

    public static void main(String[] args) throws MessagingException,
    UnsupportedEncodingException {

Properties mailProps = new Properties();

mailProps.put("mail.smtp.from", "butterscotchdreamer23@gmail.com");
mailProps.put("mail.smtp.host", "smtp.gmail.com");
mailProps.put("mail.smtp.ssl.trust", "smtp.gmail.com");
mailProps.put("mail.smtp.port", "465");
mailProps.put("mail.smtp.auth", true);
mailProps.put("mail.smtp.starttls.enable", "true");

Session mailSession = Session.getDefaultInstance(mailProps, new Authenticator() {


    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("butterscotchdreamer23@gmail.com", "password");
    }

});


MimeMessage message = new MimeMessage(mailSession);

//set the email sender
message.setFrom(new InternetAddress("butterscotchdreamer23@gmail.com"));

//set the email recipients
String[] emails = { "butterscotchdreamer23@gmail.com" };

InternetAddress dests[] = new InternetAddress[emails.length];
for (int i = 0; i < emails.length; i++) {
    dests[i] = new InternetAddress(emails[i].trim().toLowerCase());
}
message.setRecipients(Message.RecipientType.TO, dests);

//set the email subject
message.setSubject("test");

//set the email content
message.setText("this is a test");

//send
System.out.println("sending...");
Transport.send(message);
System.out.println("done sending email!");

}
}  

错误:

Exception in thread "main" 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:2041)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
at javax.mail.Service.connect(Service.java:386)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at com.brighamcampbell.sunrisegundersonmail.Mail.main(Mail.java:56)

感谢您的耐心等待!

0 个答案:

没有答案