7

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 = 'xxxxx@gmail.com'
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")
sandy
  • 181
  • 2
  • 3
  • 12
  • 2
    Did you call the function send_message()? – lqhcpsgbl Jan 10 '15 at 08:08
  • Does `mail -s ...` work from the command-line on your machine? If not; `subprocess` won't make it work. You could [send email using `smtplib`](http://stackoverflow.com/a/20787826/4279) – jfs Jan 10 '15 at 16:04

1 Answers1

14

Your function may not be called, try this code :

import subprocess

recipient = 'xxxxx@gmail.com'
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.

lqhcpsgbl
  • 3,694
  • 3
  • 21
  • 30
  • Seeing the below error if run in windows `Traceback (most recent call last): File "C:/Python34/Scripts/sending_gmail_3.py", line 12, in send_message(recipient, subject, body) File "C:/Python34/Scripts/sending_gmail_3.py", line 10, in send_message stdin=subprocess.PIPE) File "C:\Python34\lib\subprocess.py", line 858, in __init__ restore_signals, start_new_session) File "C:\Python34\lib\subprocess.py", line 1111, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified` – sandy Jan 10 '15 at 10:10
  • 3
    @sandy Of course. The `mail` command does not exist in Windows. – Jonas Gröger Jun 08 '17 at 14:33
  • 1
    In Python 3.x, change to `body = b'testing mail through python'` to work – kateryna Apr 22 '19 at 08:15
  • @iqhcpsgbl = how can we add attachment in the above example? I need to attach csv... – viki Dec 07 '21 at 01:14