版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/guimotion/article/details/80801136
有时候需要获取电脑的外网地址,本人操作电脑很简单,打开网页-》百度-》IP地址。
编程环境:Python 3.6
但是如何通过脚本自动获取并发送邮件到指定邮箱,这里简单实现就是使用Python了。
废话不多说,我们来看实际代码
#=================================================================
#获取外网IP地址并发送给邮箱地址
#=================================================================
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#导入代码库
import smtplib
import requests
import time, os, sched
import re
from email.mime.text import MIMEText
from email.utils import formataddr
# 发件人邮箱账号
my_sender='**********@qq.com'
# 发件人邮箱密码
my_pass = 'mmmmmmaaaaaaaaaa'
my_user='**********@qq.com'
def perform_command(cmd, inc):
os.system(cmd)
def timming_exe(cmd, inc = 60):
# enter用来安排某事件的发生时间,从现在起第n秒开始启动
schedule.enter(inc, 0, perform_command, (cmd, inc))
# 持续运行,直到计划时间队列变成空为止
schedule.run()
#获取IP地址
def get_out_ip():
print("读取IP地址=>")
url = r'http://www.net.cn/static/customercare/yourip.asp'
readT = requests.get(url)
Readtxt = readT.text
pattern = re.compile('<h2>[0-9]+.[0-9]+.[0-9]+.[0-9]+</h2>')
showv=pattern.search(Readtxt)
#print(Readtxt)
print(showv)
return Readtxt
#发送邮件代码
def mail():
ret=True
try:
ipmsg="当前IP地址是:"+get_out_ip()
msg=MIMEText(ipmsg,'plain','utf-8')
msg['From']=formataddr(["FromXGRobots",my_sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
msg['To']=formataddr(["XGmail",my_user]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号
msg['Subject']="家庭服务器IP报告信息" # 邮件的主题,也可以说是标题
server=smtplib.SMTP_SSL("smtp.qq.com", 465) # 发件人邮箱中的SMTP服务器,端口是25
server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号、邮箱密码
server.sendmail(my_sender,[my_user,],msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
server.quit() # 关闭连接
except Exception: # 如果 try 中的语句没有执行,则会执行下面的 ret=False
ret=False
return ret
schedule = sched.scheduler(time.time, time.sleep)
#主代码发送并循环
while True:
ret=mail()
if ret:
print("邮件发送成功")
else:
print("邮件发送失败")
print("show time after 600 seconds:")
timming_exe("echo %time%", 600)
源码中,我们重点讲解如下代码设置
# 发件人邮箱账号
my_sender='**********@qq.com'
# 发件人邮箱密码
my_pass = 'mmmmmmaaaaaaaaaa'
my_user='**********@qq.com'
my_sender=发邮件的邮箱,就是你的qq邮箱
my_user=接收件的邮箱,就是你目标发送的邮箱
my_pass =发邮件的授权码,这个需要到你的邮箱中生成。在你邮箱中,设置-》账号设置中进行生成授权码
程序运行结果:
程序点击运行-》邮件发送成功
邮箱查看-》邮件正常发送并接受到!
本项目测试就到这里,不懂的地方请留言。。。
谢谢大家的查看,喜欢我的朋友,点击关注哦!