How to send mail through mailx & subprcoess?

I am EE trying to write a script to make checking files easier with Python. For some reason, our IT experts will not allow me to access our smtp server and will allow me to send mail through mailx. So, I thought about starting mailx from Python and sending it the same way as in my console. Alas, this gives an opportunity. See Linux Log below:

***/depot/Python-3.1.1/bin/python3.1
Python 3.1.1 (r311:74480, Dec  8 2009, 22:48:08) 
[GCC 3.3.3 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> process=subprocess.Popen('echo "This is a test\nHave a loook see\n" | mailx -s "Test Python" mymail@mycomopany.com')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/depot/Python-3.1.1/lib/python3.1/subprocess.py", line 646, in __init__
    errread, errwrite)
  File "/depot/Python-3.1.1/lib/python3.1/subprocess.py", line 1146, in _execute_child
    raise child_exception***

I'm new to Python (now migrating with PERL). Any thoughts?

+3
source share
3 answers

you can use smtplib

import smtplib
# email options
SERVER = "localhost"
FROM = "root@example.com"
TO = ["root"]
SUBJECT = "Alert!"
TEXT = "This message was sent with Python smtplib."


message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

server = smtplib.SMTP(SERVER)
server.set_debuglevel(3)
server.sendmail(FROM, TO, message)
server.quit()

If you really want to use a subprocess (which I recommend)

import subprocess
import sys
cmd="""echo "test" | mailx -s 'test!' root"""
p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output, errors = p.communicate()
print errors,output
+5
source

You are using cas subprocess.call. How:

subprocess.call(["mailx", "-s", "\"Test Python\"", "mymail@mycomopany.com"])

+2

The Lior Dagan code was close to correct / functional: there was no error in this approach shell=True kwargin the call subprocess.Popen. Anyone who is really considering this approach should be aware that the documentation subprocesswarns that:

Invoking the system shell with shell=True can be a security hazard if combined with untrusted input.

F0RR and ghostdog74 are generally preferred because they are more reliable and secure.

0
source

Source: https://habr.com/ru/post/1727613/


All Articles