以下是我发送电子邮件的行为
已编辑的代码
public class EmailAlerts{
public static Session session=null;
public static final String fromAddr="from@gmail.com";
public static final String host = "smtp.gmail.com";
public static final String password="dfd";
public static MimeMessage message= null;
public EmailAlerts() {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromAddr,password);
}
});
}
/**
* @param args
*
*
*/
public static void sendNotification( String toAddress)
{
try {
message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromAddr));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(toAddress));
message.setSubject("Exchange Rate Notification!");
message.setText("The best rates are :");//+body. Need to add date from the Map/List with the rates in descending order!
Transport.send(message);
}
catch ( MessagingException e) {
// TODO Auto-generated catch block
//Need to write a custom exception handler
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
sendNotification("toAddr@gm.com");
System.out.println("Done!");
}
但是,我在第50行遇到一个例外,说SMTP主机正在尝试连接到localhost
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25, response: 421
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1270)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
at javax.mail.Service.connect(Service.java:275)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at javax.mail.Transport.send0(Transport.java:168)
at javax.mail.Transport.send(Transport.java:98)
at com.business.alerts.EmailAlerts.sendNotification(EmailAlerts.java:50)
at com.business.alerts.EmailAlerts.main(EmailAlerts.java:64)
当我真正尝试连接到Gmail时。
有什么想法吗?
答案 0 :(得分:-1)
属性mail.smtp.port
应设置为465。
答案 1 :(得分:-1)
我正在使用你在我的应用程序中显示的确切代码,它完全正常。
然而,我看到的唯一区别是,我使用的是有效“来自”地址和有效密码。我能想到的唯一另一个原因是您的系统上阻止了端口465上的传出流量,但您显示的错误代码也没有提示。
421 <domain> Service not available, closing transmission channel
您可以尝试使用有效的“发件人”地址,看看是否适合您。