相对新手编程。我正在尝试编写一个pingIP地址的程序。当主机联机时,它不执行任何操作,但在脱机时,它会向收件人发送电子邮件。但是,它每次都会发送电子邮件 - 在线和离线!我知道我已经很接近了,任何帮助都会很棒!代码片段...
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 OFFLINEn");
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,"
+ "nn 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);
}
}
您的消息部分不在 else 语句的范围内。如果您不使用大括号表示 if/else/for/等,则只考虑下一行。只需将其放入{}
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 OFFLINEn");
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,"
+ "nn 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);
}
}
}
您的 try 块与 if 语句无关。Java 中一个好的做法是始终对 if/else 块使用大括号,如果不使用大括号,则只会执行有关 if/else 响应的第一行代码。
例如,在以下代码中
if(someTest())
doSomething();
doSomethingElse();
doSomethingElse()
将始终执行。
在此代码中:
if(someTest()){
doSomething();
doSomethingElse();
}
doSometingElse() 只有在 someTest() 为 true 时才执行