0

Running on a Linux system. I have a executable .jar file that I am trying to make the output into the body of a email that I am having my python program send. However, though this program executes, the email is received with nothing in the body. So the output of the .jar is lost in the subprocess.

import smtplib
import subprocess

s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.ehlo()
# login cred
username='Sample@gmail.com'
password='password'
s.login(username,password)
# email objects
replyto='sample@sample.com'
sendto=['export@sample.com']
sendtoShow='sample@sample.com' 
subject='Example Subject'
content=subprocess.run(['java', '-jar', 'Example.jar'], stdout=subprocess.PIPE)
mailtext='From: '+replyto+'\r\nTo: '+sendtoShow+'\r\n'
mailtext=mailtext+'Subject:'+subject+'\r\n\r\n'+content.stdout.decode("utf-8")
s.sendmail(replyto, sendto, mailtext)
rslt=s.quit()
print('Sendmail result=' + str(rslt[1]))

Problem solved and reflected above.

3 Answers3

0

Check the lines where you are performing string concatenation.

mailtext='From: '+replyto+'\nTo: '+sendtoShow+'\n'
mailtext=mailtext+'Subject:'+subject+'\n'+content
...
print('Sendmail result=' + str(rslt[1]))

Are any of these lines attempting to concatenate str and int objects together? That is, is any of replyto, sendtoShow, mailtext, subject, or content actually int objects? To avoid guessing, simply cast them to str like you do at the last line.

miara
  • 847
  • 1
  • 6
  • 12
0

subprocess.call returns the return code of the program, not the output of the program. So in your case "content" is an int not a string.

try something like:

content=subprocess.run(['java', '-jar', 'Example.jar'], stdout=subprocess.PIPE)
mailtext='From: '+replyto+'\r\nTo: '+sendtoShow+'\r\n'
mailtext=mailtext+'Subject:'+subject+'\r\n\r\n'+content.stdout.decode("utf-8")
cshortridge
  • 66
  • 1
  • 4
  • When I do that I get an error on line: mailtext=mailtext+'Subject:'+subject+'\n'+content.stdout - TypeError: Can't convert 'bytes' object to str implicitly – Dan B Raelin Feb 26 '19 at 00:15
  • My bad, you have to convert the byte array to a string: ```content.stdout.decode("utf-8")``` I've edited the original response, you may need a different encoding than utf-8 depending on your circumstances – cshortridge Feb 26 '19 at 14:24
  • well good news is the edit made it run without any errors, however it does not reach the desired output. The email sends but does not show the output of the .jar program. I tried different encoding methods as well. – Dan B Raelin Feb 26 '19 at 17:00
  • I may be wrong, but I think the message fields expect ```\r\n``` not just ```\n```. and ```\r\n\r\n``` after the last field definition before the main body. I'll update my original answer to reflect what I mean – cshortridge Feb 27 '19 at 15:08
0

subprocess.call returns exit code, not the stdout. You need to use popen method.