【发布时间】:2019-06-11 13:21:12
【问题描述】:
编程的相对新手。我正在尝试编写一个 ping IP 地址的程序。当主机在线时它什么也不做,但当它离线时它会向收件人发送一封电子邮件。然而,它每次都发送电子邮件 - 在线和离线!我知道我很接近,任何帮助都会很棒! 代码 sn-p...
final String username = "myemail@gmail.com";
final String password = "Password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
InetAddress i = InetAddress.getByName(ipAddress);
System.out.println("Sending Ping Request to " + ipAddress);
if (i.isReachable(5000)) //5 second limit
System.out.println("Host is online \n");
else
System.out.println("HOST IS OFFLINE\n");
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("myemail@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("receiveremail@hotmail.com"));
message.setSubject("Project Test Mail");
message.setText("Test Mail,"
+ "\n\n Sent From sendMail.java application");
Transport.send(message);
System.out.println("Mail Sent to receiveremail@hotmail.com "
+ ipAddress);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
【问题讨论】:
-
这就是为什么你应该将单行语句放在大括号中的 if/else 语句中!
标签: java ip-address ping