首页 > 随笔档案 > 树莓派自动发送ip到邮箱

树莓派自动发送ip到邮箱

Publish:

树莓派自动发送IP到邮箱

sudo vi send_ip.py

#!/usr/bin/env python3
#-*-coding: utf-8-*-
import socket
import time
import smtplib
import urllib.request
from email.mime.text import MIMEText
from email.header import Header

def sendEmail(smtpserver,username,password,sender,receiver,subject):
        message = MIMEText(subject, '', 'utf-8')
        message['From'] = Header(sender, 'utf-8')
        message['To'] =  Header(','.join(receiver), 'utf-8')
        subject = 'pi ipaddr'
        message['Subject'] = Header(subject, 'utf-8')

        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(smtpserver, 25)
            smtpObj.login(username,password)
            smtpObj.sendmail(sender, receiver, message.as_string())
            print("Yes")
        except Exception as err:
            print(err)
        finally:
            print("end!")


def check_network():
        while True:
            try:
                result=urllib.request.urlopen('http://baidu.com').read()
                # print(result)
                print("Network is Ready!")
                break
            except Exception as e:
                print(e)
                print("Network is not ready,Sleep 5s...")
                time.sleep(5)
        return True

def get_ip_address():
        s =socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.connect(("8.8.8.8",80))
        ipaddr=s.getsockname()[0]
        s.close()
        return ipaddr

if  __name__ == '__main__' :
        time.sleep(120)
        check_network()
        ipaddr= get_ip_address()
        print(ipaddr)
        sendEmail("smtp.exmail.qq.com",'pi@xxx.cn','password','pi@xxx.cn',['youremail@xxx.cn'],'IP Address of Raspberry PI:' + ipaddr)

sudo chmod 777 ./send_ip.py

修改 rc.local

sudo vi /etc/rc.local

su pi -c "exec /send_ip.py"
exit 0

需要开机等待两分钟保证已经获取到IP.

声明: 本文采用 BY-NC-SA 授权。转载请注明转自: levy