我有桌面应用程序,我在发送邮件时遇到此错误javax.mail.MessagingException:无法连接到SMTP主机:smtp.gmail.com,port:587;嵌套异常是:java.net.ConnectException:连接被拒绝:连接
~code~
String host="smtp.mail.yahoo.com";
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.host",host);
props.put("mail.smtp.host", host);
props.put("mail.stmp.user", "abc@yahoo.ca");//User name
//To use TLS
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.password", "mypassword"); //Password
props.put("mail.smtp.socketFactory.fallback", "false");
Session session1 = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "abc@yahoo.ca";
String password = "mypassword";
return new PasswordAuthentication(username, password);
}
});
MimeMessage msg = new MimeMessage(session1);
String from = "abc@yahoo.ca";
String subject = "Testing...";
msg.setFrom(new InternetAddress(from));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
msg.setSubject(subject);
Transport.send(msg);
答案 0 :(得分:1)
YahooMail smtp port是465
或587
添加: -
props.put("mail.smtp.port", "465");
或
props.put("mail.smtp.port", "587");
答案 1 :(得分:0)
您找到了JavaMail FAQ吗?
这些条目将有所帮助:
答案 2 :(得分:0)
试试这个:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com";
// Sender's email ID needs to be mentioned
String from = "web@gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}