相对较新的编程。我正在尝试编写一个ping IP地址的程序。当主机在线时它什么都不做,但在离线时它会向收件人发送一封电子邮件。然而,它每次都会发送电子邮件 - 在线和离线!我知道我很亲密,任何帮助都会很棒!代码片段......
final String username = "[email protected]";
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("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
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 [email protected] "
+ ipAddress);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
您的消息部分不在您的else语句范围内。如果不对if / else / for / etc使用大括号,则只考虑下一行。把它放在{}
final String username = "[email protected]";
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("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
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 [email protected] "
+ ipAddress);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
您的try块与if语句无关。 java中的一个好习惯总是使用if / else块的花括号,如果不使用花括号,则只会执行关于if / else响应的第一行代码。
例如,在以下代码中
if(someTest())
doSomething();
doSomethingElse();
doSomethingElse()
将始终执行。
并在此代码中:
if(someTest()){
doSomething();
doSomethingElse();
}
doSometingElse()仅在someTest()为true时执行