📜  Python|网站启动时收到电子邮件提醒(1)

📅  最后修改于: 2023-12-03 15:04:28.091000             🧑  作者: Mango

Python | 网站启动时收到电子邮件提醒

在日常开发中,我们时常需要监测网站是否正常运行,发现是否存在异常。我们可以通过编写程序来实现这个功能,并加上邮件提醒,方便及时处理问题。以下是一个Python脚本示例,可以在网站启动时发送邮件提醒:

实现步骤
  1. 准备需要模块
  • smtplib: 发送邮件所需模块
  • email.mime.text: 设置邮件内容格式
  • logging: 记录日志
  • socket: 连接网站所需模块
import smtplib
from email.mime.text import MIMEText
import logging
import socket
  1. 设置日志
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.INFO)
  1. 定义网站
website = "http://www.example.com"
  1. 定义函数,检测网站是否正常
def check_website():
    try:
        logging.info("Connecting to the website...")
        response = urllib.request.urlopen(website, timeout=10)
        logging.info("Website is OK.")
        return True
    except socket.timeout:
        logging.error("Website connection timed out.")
        return False
    except:
        logging.error("Website is down.")
        return False
  1. 定义函数,发送邮件提醒
def send_email(to, subject, body):
    smtp_server = 'smtp.example.com'
    from_email = 'you@example.com'
    password = 'password'
    message = MIMEText(body)
    message['Subject'] = subject
    message['From'] = from_email
    message['To'] = to
    try:
        logging.info(f'Sending email to {to}...')
        mail_server = smtplib.SMTP_SSL(smtp_server, 465)
        mail_server.login(from_email, password)
        mail_server.sendmail(from_email, [to], message.as_string())
        mail_server.quit()
        logging.info('Email sent.')
    except:
        logging.error('Unable to send email.')
  1. 定义主函数
if __name__ == '__main__':
    if check_website():
        subject = 'Website is up.'
        body = 'Your website is up and running.'
    else:
        subject = 'Website is down!'
        body = 'Your website is down!\n\nPlease check the website.'
    send_email('recipient@example.com', subject, body)
代码片段
import smtplib
from email.mime.text import MIMEText
import logging
import socket
import urllib.request

logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.INFO)

website = "http://www.example.com"

def check_website():
    try:
        logging.info("Connecting to the website...")
        response = urllib.request.urlopen(website, timeout=10)
        logging.info("Website is OK.")
        return True
    except socket.timeout:
        logging.error("Website connection timed out.")
        return False
    except:
        logging.error("Website is down.")
        return False

def send_email(to, subject, body):
    smtp_server = 'smtp.example.com'
    from_email = 'you@example.com'
    password = 'password'
    message = MIMEText(body)
    message['Subject'] = subject
    message['From'] = from_email
    message['To'] = to
    try:
        logging.info(f'Sending email to {to}...')
        mail_server = smtplib.SMTP_SSL(smtp_server, 465)
        mail_server.login(from_email, password)
        mail_server.sendmail(from_email, [to], message.as_string())
        mail_server.quit()
        logging.info('Email sent.')
    except:
        logging.error('Unable to send email.')

if __name__ == '__main__':
    if check_website():
        subject = 'Website is up.'
        body = 'Your website is up and running.'
    else:
        subject = 'Website is down!'
        body = 'Your website is down!\n\nPlease check the website.'
    send_email('recipient@example.com', subject, body)
总结

以上就是通过 Python 监测网站并发送邮件提醒的示例,对于网站监测和异常处理有很大帮助,同时也提升了网站的可靠性和稳定性。开发者们可以根据实际需求进行修改和扩展,打造完善的网站运维管理系统。