文章目录
前言
在服务器运行小脚本时,会经常使用输出日志文件查看运行情况。为了方便,简化通知,就使用到了以下俩种方法,谨为记录。如果你有其他或者更好的方法,可以分享给我,致谢!
server酱:微信通知
server酱,具体使用以及注意事项可以查看官网。以下代码只是会通知标题信息,详情内容没有相应代码。
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Create by LEE
*
* @description: 发送微信通知
*/
public class Notify {
public static boolean sendNotifyGet(String note) {
boolean notify_result = false;
try {
URL url = new URL(SCKEY_URL + note);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(20 * 1000);
conn.setReadTimeout(60000);
conn.connect();
if (conn.getResponseCode() == 200) {
notify_result = true;
} else {
try {
Thread.sleep(1000 * 65);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendNotifyGet(note);
}
} catch (IOException e) {
e.printStackTrace();
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
sendNotifyGet(note);
}
return notify_result;
}
}
电子邮件通知
之前参的考链接找不到了!这里会使用到mail.jar包,里面的配置请自行百度即可,在配置不同的邮箱时有待区别,区别请看注释。
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
/**
* Create by LEE on 2020/9/27 22:25
*
* @description: qq邮箱发送邮件通知示例,其他邮箱类似
*/
public class Mail {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
//协议
prop.setProperty("mail.transport.protocol", "smtp");
//服务器
prop.setProperty("mail.smtp.host", "smtp.qq.com");
//端口
prop.setProperty("mail.smtp.port", "587");
//使用smtp身份验证
prop.setProperty("mail.smtp.auth", "true");
//获取Session对象
Session s = Session.getDefaultInstance(prop, new Authenticator() {
//此访求返回用户和密码的对象
@Override
protected PasswordAuthentication getPasswordAuthentication() {
PasswordAuthentication pa = new PasswordAuthentication("发送邮箱@qq.com", "授权码,可以认为是密码");
return pa;
}
});
//设置session的调试模式,发布时取消
s.setDebug(true);
MimeMessage mimeMessage = new MimeMessage(s);
try {
mimeMessage.setFrom(new InternetAddress("发送邮箱@qq.com"));
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("接收邮箱@qq.com"));
//设置主题
mimeMessage.setSubject("邮件主题");
mimeMessage.setSentDate(new Date());
//设置内容
mimeMessage.setText("邮件内容");
mimeMessage.saveChanges();
//发送
Transport.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}