这里的新人。我试图通过java发送电子邮件,我使用的以下代码来自此站点;
public class NewClass extends Object{
public static void main(String [] args)
{
try{
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.mail.yahoo.com"); // for gmail use smtp.gmail.com
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("abcd@yahoo.com", "abcd");
}
});
mailSession.setDebug(true); // Enable the debug mode
Message msg = new MimeMessage( mailSession );
//--[ Set the FROM, TO, DATE and SUBJECT fields
msg.setFrom( new InternetAddress( "abcd@yahoo.com" ) );
msg.setRecipients( Message.RecipientType.TO,InternetAddress.parse("efgh@gmail.com") );
msg.setSentDate( new Date());
msg.setSubject( "Hello World!" );
//--[ Create the body of the mail
msg.setText( "Hello from my first e-mail sent with JavaMail" );
//--[ Ask the Transport class to send our mail message
Transport.send( msg );
}catch(Exception E){
System.out.println("Unable to send Mail");
System.out.println( E );
}
} }
这是我得到的错误:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.mail.yahoo.com, port: 587; nested exception is: java.net.SocketException: Connection reset
我在这里做错了什么?任何帮助将不胜感激,TIA! PS。抱歉任何格式错误。
答案 0 :(得分:0)
smtp.mail.yahoo.com
的SSL SMTP端口为465
,而不是587
。
更改您的代码:
props.put("mail.smtp.port", "587");
props.put("mail.smtp.socketFactory.port", "587");
到
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");