树莓派开机发送IP地址到邮箱

针对无屏幕的树莓派用户一般都会用到SSH远程连接,要进行SSH连接首先要知道树莓派的IP地址,本文就讲解怎么使用python以邮件的方式把树莓派的IP地址发送到我们指定的邮箱中。

下面附上我的代码(已经过验证)

# -*- coding:utf-8 -*-
import socket
import smtplib
import urllib.request
import urllib.error
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

# 第三方SMTP服务
mail_host = 'smtp.163.com'
mail_user = '****@163.com' # 你的发送邮箱
mail_pass = 'san***' # 授权码,并非是登陆吗。需要你进入163进行设置

sender = '***@163.com' # 发送邮箱
receivers = ('*****@qq.com',) # 接收邮箱

content = 'ip地址'
title = '树莓派ip地址'

def sendEmail(ip_address):
    message = MIMEText(ip_address, 'plain', 'utf-8') # 内容,格式,编码
    message['From'] = "{}".format(sender)
    message['To'] = ",".join(receivers)
    message['Subject'] = title

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465) # 启用SSL发信
        smtpObj.login(mail_user, mail_pass) # 登陆验证
        smtpObj.sendmail(sender, receivers, message.as_string())
        print('Email 发送成功!')
    except smtplib.SMTPException as e:
        print(e)

# 检查网络连接
def check_network():
    for i in range(0, 5):
        try:
            result = urllib.request.urlopen('http://www.baidu.com')
            print('Network is Ready!')
            break
        except Exception as e:
            print(e)
            print("Network is not ready, Sleep 5s....")
            time.sleep(5*10)
    else:
        print("Sorry that pi isn't connectted to Internet now")
        return False
    return True


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

if __name__ == '__main__':
    if check_network():
        ipaddr = get_ip_address()
        sendEmail(ipaddr)
    else:
        print('网络故障')

 

评论

  • 还没有任何评论,来说两句吧。

  • 0%