测试环境 Ubuntu 18.4.6 jetson nano
1.编写python代码发送邮件 文件名a.python
# !/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import socket
import smtplib
from email.mime.text import MIMEText
from email.header import Header
#测试网络是否联通
def ping():
url = "http://www.baidu.com" # 要测试的网站地址
timeout = 5 # 设置请求超时时间,单位为秒
try:
response = requests.get(url, timeout=timeout)
response.raise_for_status() # 如果返回码不是200,则抛出异常
except Exception as e:
return False
else:
#print(response.raise_for_status())
return True
#获取ip
def get_host_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip
#邮箱发送ip
def send(ip):
mail_host = "smtp.qq.com" # 设置的邮件服务器host必须是发送邮箱的服务器,与接收邮箱无关。
mail_user = "978*****42@qq.com" # qq邮箱登陆名
mail_pass = "uwwt****ahg" # 开启stmp服务的时候并设置的授权码,注意!不是QQ密码。
sender = '978****442@qq.com' # 发送方qq邮箱
receivers = ['978****42@qq.com'] # 接收方qq邮箱
message = MIMEText(ip, 'plain', 'utf-8')
message['From'] = Header("name <97**42@qq.com>") # 设置显示在邮件里的发件人,应为此格式
message['To'] = Header("wowo", 'utf-8') # 设置显示在邮件里的收件人
subject = 'ip'
message['Subject'] = Header(subject, 'utf-8') # 设置主题和格式
try:
smtpobj = smtplib.SMTP_SSL(mail_host, 465) # 本地如果有本地服务器,则用localhost ,默认端口25,腾讯的(端口465或587)
smtpobj.set_debuglevel(1)
smtpobj.login(mail_user, mail_pass) # 登陆QQ邮箱服务器
smtpobj.sendmail(sender, receivers, message.as_string()) # 发送邮件
print("邮件发送成功")
smtpobj.quit() # 退出
except smtplib.SMTPException as e:
print("Error:无法发送邮件")
print(e)
if __name__ == '__main__':
while True:
if(ping()):
ip = get_host_ip()
send(ip)
break
2.编写开机服务文件
sudo gedit /lib/systemd/system/my_program.service
[Unit]
Description=My_Python_Program
After=multi-user.target
[Service]
Type=idle
ExecStart=/usr/bin/python3 /home/yong/Desktop/a.py
[Install]
WantedBy=multi-user.target
注:/home/yong/Desktop/a.py 为python文件路径
3.修改为可执行权限
sudo chmod +x /lib/systemd/system/my_program.service
sudo chmod +x /home/yong/Desktop/a.py
4.测试是否成功
#重载系统服务
sudo systemctl daemon-reload
#服务开启
sudo systemctl start my_program.service
#查看服务状态
sudo systemctl status my_program.service
#设置为开机启动
sudo systemctl enable my_program.service
5.sudo systemctl status my_program.service 如果出现报错
# 看谁否报错 一般是没有安装requests库
pip3 install requests安装一下就行
注:注意 sudo pip install 与 pip install 与pip3的区别