python - 邮件发送
因为公网ip是动态的,想做一个在ip发生改变后邮件提醒
1. 首先需要开启smtp服务
开启后复制授权密码
2. 邮件发送
import smtplib
from email.mime.text import MIMEText
From = 'ZZZZZZZZZZZZZZZZ@163.com' # 发件人邮箱
To = From
pwd = 'ZZZZZZZZZZZZZZZZ' # 授权码
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com',25)
print(smtp.login(From, pwd))
mail = MIMEText('''内容''') # 内容
mail['Subjcet'] = '主题' # 主题
mail['From'] = 'AI' # 发件人(说明作用)
mail['To'] = 'Master' # 接收者(说明作用)
smtp.sendmail(From, To, mail.as_string())
print('send email success')
smtp.quit()
3. 检查ip后定时发送
import smtplib
import requests
import random
import datetime
from email.mime.text import MIMEText
from time import sleep
From = 'ZZZZZZZZZZZZZZZZ@163.com' # 发件人邮箱
To = From
pwd = 'ZZZZZZZZZZZZZZZZ' # 授权码
ip = ''
urls = ['https://checkip.amazonaws.com/', 'http://ip.42.pl/raw']
while True:
sleep(10)
res = requests.get(random.choice(urls))
if ip == res.text.strip():
print(f'now ip: {ip} ', end='')
print(f"now time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
continue
ip = res.text.strip()
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com',25)
print(smtp.login(From, pwd))
mail = MIMEText(f'new ip: {ip}') # 内容
mail['Subjcet'] = 'AI' # 主题
mail['From'] = 'AI' # 发件人(说明作用)
mail['To'] = 'Master' # 接收者(说明作用)
smtp.sendmail(From, To, mail.as_string())
print('send email success.')
print(f'new ip: {ip} ', end='')
print(f"now time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
smtp.quit()