2

I'm trying to make my pi send email about it's IP via Gmail, based on this link.

From what I've read in this thread I should be getting string output of shell in 'output1' variable when using .stdout.decode(). But unlike usual strings like 'Hello World' - Which show no error in MIMEText() - MIMEText(output1) shows following error.

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'

Can someone explain why Shell output always lack 'encode' attribute despite decoding it into 'us-ascii', and how to properly handle Shell output to MIMEText()?


Source Code as Follows:

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()

wovano
  • 4,543
  • 5
  • 22
  • 49
jupiterbjy
  • 2,882
  • 1
  • 10
  • 28

1 Answers1

1

Your statement output1.stdout.decode('us-ascii') does not have any effect. It decodes the output, but the result is never stored. In the line message = MIMEText(output1) you pass the result of subprocess.run(), which is an object of type CompletedProcess. You should have passed the decoded text instead. So:

decoded_output = output1.stdout.decode('us-ascii')
message = MIMEText(decoded_output)
wovano
  • 4,543
  • 5
  • 22
  • 49
  • If you only have a single body part, there is no need to wrap it in a multipart container. Like the name implies, multipart containers are useful when you have multiple parts. – tripleee Jun 02 '19 at 12:55
  • 1
    I'm really sorry for late reply! I didn't know I had to assign decoded value to variable, it works now flawlessly. Since I lack reputation my vote up won't show up but I surely did. Thanks for help! :) – jupiterbjy Jun 04 '19 at 16:30