Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send a mail via mailx & subprocess?

I am EE, trying to write a script to simplify file checks using Python.

For some reason, our IT will not let me gain access to our SMTP server, and will only allow sending mail via mailx. So I've thought of running mailx from Python and send it, in the same way that it works in my console. Alas, it gives an exception. See Linux log below:

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" [email protected]')
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 am a newbie to Python (now migrating from Perl). Any thoughts?

like image 803
Lior Dagan Avatar asked Jan 07 '10 13:01

Lior Dagan


People also ask

What is difference between mailx and mail?

Mailx is more advanced than “mail”. Mailx supports attachments by using the “-a” parameter. Users then list a file path after the “-a” parameter. Mailx also supports POP3, SMTP, IMAP, and MIME.

How do I specify an address in mailx?

You can use the "-r" option to set the sender address: mailx -r [email protected] -s ...


2 Answers

you can use smtplib

import smtplib
# email options
SERVER = "localhost"
FROM = "[email protected]"
TO = ["root"]
SUBJECT = "Alert!"
TEXT = "This message was sent with Python's 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 subprocess( which i advise against)

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
like image 81
ghostdog74 Avatar answered Oct 13 '22 22:10

ghostdog74


You cas use subprocess.call. Like:

subprocess.call(["mailx", "-s", "\"Test Python\"", "[email protected]"])

Details here

like image 1
F0RR Avatar answered Oct 13 '22 22:10

F0RR