Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing shell mail command using python

I have used the following code to send an email as suggested in one of the post on the similar topic. But the mail has not been sent. Any suggestions?

import subprocess
recipient = '[email protected]'
subject = 'test'
body = 'testing mail through python'
def send_message(recipient, subject, body):
    process = subprocess.Popen(['mail', '-s', subject, recipient],
                               stdin=subprocess.PIPE)
    process.communicate(body)

print("sent the email")
like image 711
sandy Avatar asked Jan 10 '15 07:01

sandy


People also ask

How do you execute a shell command in Python?

If you need to execute a shell command with Python, there are two ways. You can either use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.

How do I use Python to send an email?

Set up a secure connection using SMTP_SSL() and . starttls() Use Python's built-in smtplib library to send basic emails. Send emails with HTML content and attachments using the email package.

How do you run a shell command from Python and get the output?

In Python 3.5+, check_output is equivalent to executing run with check=True and stdout=PIPE , and returning just the stdout attribute. You can pass stderr=subprocess. STDOUT to ensure that error messages are included in the returned output.

How do I run a shell command in Python using subprocess?

Python Subprocess Run Function The subprocess. run() function was added in Python 3.5 and it is recommended to use the run() function to execute the shell commands in the python program. The args argument in the subprocess. run() function takes the shell command and returns an object of CompletedProcess in Python.


1 Answers

Your function may not be called, try this code :

import subprocess

recipient = '[email protected]'
subject = 'test'
body = 'testing mail through python'

def send_message(recipient, subject, body):
    try:
      process = subprocess.Popen(['mail', '-s', subject, recipient],
                               stdin=subprocess.PIPE)
    except Exception, error:
      print error
    process.communicate(body)

send_message(recipient, subject, body)

print("sent the email")

May works. Good luck.

like image 90
lqhcpsgbl Avatar answered Sep 17 '22 23:09

lqhcpsgbl