我使用以下Java代码发送电子邮件.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
String to = "abcd@gmail.com";
String from = "web@gmail.com";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("smtp.gmail.com", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to))
message.setSubject("This is the Subject Line!");
message.setText("This is actual message");
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
当我运行该文件时,我收到以下错误:
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
如果有人可以帮助我,我真的很感激.
如何解决ConnectException?
解决方法:
我可以看到您正在尝试将Gmail用作SMTP服务器.这行不正确:
properties.setProperty("smtp.gmail.com", host);
您使用主机名作为属性名称,这是不正确的.因为您没有设置mail.smtp.host属性,JavaMail会尝试连接到“localhost”.改为设置以下属性:
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.user", "username"); // User name
properties.put("mail.smtp.password", "password"); // password
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");