Executing shell mail command using python

10.2k Views Asked by At

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")
1

There are 1 best solutions below

4
On BEST ANSWER

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.