如何使用Java向用户发送电子邮件?



我使用这个代码发送电子邮件给用户

static void SendEmail(String email) 
{
System.out.println(email);
String recipient = email;
String sender = "*my email*";
String host = "127.0.0.1";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try 
{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
message.setSubject("Vote Results");
message.setText("Votes have ended, here are the results: Apple:" + votes1 + " Banana:" + votes2);
Transport.send(message);
System.out.println("Sent message successfully....");
} 
catch (MessagingException e)
{
e.printStackTrace();
}
}

但是它一直返回这个异常:

com.sun.mail.util。MailConnectException:无法连接到主机端口:127.0.0.1,25;超时1;嵌套异常是:

我认为问题是你不是SMTP服务器,你不能直接发送电子邮件。你可以尝试添加Google SMTP:它是免费的,但有点限制。在代码中添加如下内容:

prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true");

相关内容

  • 没有找到相关文章

最新更新