我正在尝试让我的pi根据this link通过Gmail发送有关IP的电子邮件。
根据我在this thread中所读的内容,使用.stdout.decode()时,应该在'output1'变量中获取shell的字符串输出。但是与“ Hello World”之类的普通字符串不同-MIMEText()中没有显示错误-MIMEText(output1)显示了以下错误。
Traceback (most recent call last):
File "/home/upload/startup_mail.py", line 24, in <module>
message = MIMEText(output1)
File "/usr/lib/python3.5/email/mime/text.py", line 34, in __init__
_text.encode('us-ascii')
AttributeError: 'CompletedProcess' object has no attribute 'encode'
有人可以解释为什么Shell输出尽管将其解码为“ us-ascii”,但为什么总是缺少“ encode”属性,以及如何正确处理Shell输出为MIMEText()?
源代码如下:
import subprocess
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import datetime
to = 'xxxx@gmail.com'
user = 'xxx@gmail.com'
us_p = 'xxxx'
smtpserv = smtplib.SMTP('smtp.gmail.com',587)
smtpserv.ehlo()
smtpserv.starttls()
smtpserv.ehlo()
smtpserv.login(user, us_p)
# run command in background console and get output
output1 = subprocess.run(['ip', 'route', 'list'], stdout=subprocess.PIPE)
output1.stdout.decode('us-ascii')
today = datetime.date.today()
msg = MIMEMultipart('alternative')
message = MIMEText(output1)
msg.attach(message)
msg['Subject'] = 'Pi Booted on %s' % today.strftime('%b %d %Y')
smtpserv.sendmail(user, [to], msg.as_string())
smtpserv.quit()
答案 0 :(得分:0)
您的声明output1.stdout.decode('us-ascii')
无效。它解码输出,但结果从不存储。在message = MIMEText(output1)
行中,传递subprocess.run()
的结果,该结果是类型CompletedProcess
的对象。您应该改为传递已解码的文本。所以:
decoded_output = output1.stdout.decode('us-ascii')
message = MIMEText(decoded_output)