3

I am trying to create a simple python script which sends an email. I used this following code:

import subprocess

params = {'from':    '[email protected]',
          'to':      '[email protected]',
          'subject': 'Message subject'}

message = '''From: %(from)s
To: %(to)s
Subject: %(subject)s

Message body

''' % params

sendmail = subprocess.Popen(['/usr/share/sendmail', params['to']])
sendmail.communicate(message)

But i recive the following error message when i try to run it:

Traceback (most recent call last):
  File "/home/me/test.py", line 15, in <module>
    sendmail = subprocess.Popen(['/usr/share/sendmail', params['to']])
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
    raise child_exception
OSError: [Errno 13] Permission denied

Anyone knows a solution to this problem, or maybe a better code?

Thanks!

7
  • instead of calling the sendmail binary you could use the builtin smtp library docs.python.org/library/email-examples.html Commented Jun 29, 2012 at 6:52
  • Any special reason not to use smtplib or email modules of python? Commented Jun 29, 2012 at 7:12
  • For me it didn't threw the above error. In my system sendmail sits in /usr/sbin/sendmail, just check from the command prompt you can send mail. Commented Jun 29, 2012 at 7:13
  • @guidot no there is no particular reason i am open for suggestions. Commented Jun 29, 2012 at 7:19
  • @tuxuday i moved it to /usr/sbin/sendmail without result :/ Commented Jun 29, 2012 at 7:20

5 Answers 5

3

Instead of calling a specific process, you can if your mail is configured directly use the dedicated mail libs:

import smtplib
from email.mime.text import MIMEText

fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

# Format headers
msg['Subject'] = 'My subject'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'

# Send the message via Michelin SMTP server, but don't include the envelope header.
s = smtplib.SMTP('your mail server')
s.sendmail('[email protected]', ['[email protected]'], msg.as_string())
s.quit()

You have more python email examples in the doc.

Sign up to request clarification or add additional context in comments.

2 Comments

i get the following errormsg when i try to run it: error: [Errno 111] Connection refused.
So this is a SMTP server configuration error. Did you try with 'localhost' as a server ?
2

/usr/share/sendmail is very unusual - are you sure your sendmail binary is actually there? Normally it's at /usr/sbin/sendmail.

I'd rather use the standard library smptlib instead of calling sendmail directly if I were you.

You can use it like this to send a message:

 server = smtplib.SMTP('smtp.example.com')
 server.sendmail(fromaddr, toaddrs, msg)
 server.quit()

2 Comments

i wrote whereis sendmail in the terminal and /usr/share/sendmail is what it responded. But i have moved the sendmail folder to /usr/sbin now with the same errormsg given.
this is going off-topic, but does that sendmail actually work from the commandline?
1

Here is some code that sends emails using smtplib, and can do TLS/SSL

import smtplib
from email.MIMEText import MIMEText
from email.utils import parseaddr

class Mailer(object):
    def __init__(self, fromAddress, toAddress, password):
        self.fromAddress = parseaddr(fromAddress)[1]
        self.toAddress = parseaddr(toAddress)[1]
        self.password = password

    def send(self, subject, body):
        msg = MIMEText(body)
        msg["From"] = self.fromAddress
        msg["Reply-to"] = self.toAddress
        msg["To"] = self.toAddress
        msg["Subject"] = subject

        sender = msg["From"]
        recipient = msg["To"]

        messageText = "".join(str(msg))
        mxhost = self.lookup(sender) # lookup finds the host that you want to send to

        server = smtplib.SMTP(mxhost, 587) #port 465 or 587
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(sender, self.password)
        server.sendmail(sender, recipient, messageText)
        server.close()

Comments

0

This is my code to send email.

#coding: utf-8

import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate

def send_mail(to_list,sub,content):
    mail_host="smtp.example.com"
    mail_user="nvi"
    mail_pass="password"
    mail_postfix="example.com"
    me=mail_user + '555' +"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEText(content, _subtype='plain', _charset='utf-8')
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = to_list
    msg['Date'] = formatdate(localtime=True)
    msg['Bcc'] = '[email protected]'
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me, to_list, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print e
        return False


if __name__ == "__main__":
    send_mail('my_email_address', 'subject', 'content')

Comments

0

My program works with gMail, you can try and play around with it for anything else. You can also send SMS messages. I am attaching my code below.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
Type = input("Enter 1 for eMail, 2 for SMS: ")
toaddr = 0
if Type=='1':
   toaddr = input("Enter to address: ")
else:
   Provider = input("1 for Sprint, 2 for AT&T, and 3 for Verizon: ")
   Mobile = input("Enter the mobile number: ")
   if Provider=='1': 
      toaddr = str(Mobile) + "@messaging.sprintpcs.com"
   if Provider=='2':
      toaddr = str(Mobile) + '@txt.att.net'
   if Provider=='3':
      toaddr = str(Mobile) + ''
   print (toaddr)      
head = input("Enter your subject: ")
body = input("Enter your message: ")
fromaddr = input("Enter the 'From Address'([email protected]): ")
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = head
password = input("Enter the from address password: ")
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, password)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

I hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.