Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Python (http://www.go4expert.com/articles/python-tutorials/)
-   -   Send Email In Python (http://www.go4expert.com/articles/send-email-python-t7567/)

pradeep 27Nov2007 13:39

Send Email In Python
 

Introduction



There are two basic methods for sending an email with Python.
  1. If a mail server is running on the machine where Python is installed, simply open a pipe to the mail server and write the email as a file to that pipe. This is usually done on *nix type systems such as Linux.
  2. Use SMTP protocol to send the email. This can easily be done on either *nix or Windows type machines, providing you have access to a SMTP server. Almost anyone with Internet access has access to some SMTP server.
Examples of sending email using both techniques are explained below.

If you are planning on writing a script that can send email, for use on a computer that is accessible via Internet or other network connections, please be sure to read the cautions at the end of this article regarding security issues and spam exploits.

For both types of examples, we will use the following email message saved in a text file:

Code:

To: shabbir@g4e.com
  From: pradeep@g4e.com
  Subject: Sending Email With Python
 
  Here is the message body.
  This concludes our test.
  Deepz.
 
  - sig

Save an email similar to the one above to a file, such as mssg.txt. Make sure to replace the email addresses with valid ones that you control and can check. Note the blank line after the Subject header and before the message body begins. Such a blank line indicates the end of the email headers and the beginning of the message body.

Writing to a Pipe



Many *nix systems offer sendmail as an MTA (Mail Transfer Agent). Even systems that do not have sendmail installed, often have sendmail as an alias to the actual MTA, such as qmail or other. This is because sendmail is so ubiquitous, that even systems that do not actually have sendmail installed will set it up as an alias so that users can easily install common scripts that make the assumption that sendmail is available.

The path to sendmail is typically something like:

Code:

/usr/bin/sendmail
 
  or
 
  /usr/sbin/sendmail

If you do not know the location of sendmail on your server, you might try using the locate command at a command prompt, such as:

Code:

$ locate sendmail
Another command that can help you locate sendmail is which as follows:

Code:

$ which sendmail
Here is a Python program which opens a pipe to sendmail, opens the file with the email message in it and reads it, then writes the email data to the sendmail pipe. The Python os module, specifically the os.popen command, is used to open the pipe.

Code: Python

import os
 
  MAIL = "/usr/bin/sendmail"
 
  # get the email message from a file
  f = open('mssg.txt', 'r')
  mssg = f.read()
  f.close()
 
  # open a pipe to the mail program and
  # write the data to the pipe
  p = os.popen("%s -t" % MAIL, 'w')
  p.write(mssg)
  exitcode = p.close()
  if exitcode:
      print "Exit code: %s" % exitcode

The -t switch on the sendmail command instructs the MAIL program to take the email addresses of the recipients from the To and CC headers of the message passed to the program. So, in this case, the mail program will try to send the email to shabbir@g4e.com.

Sending via SMTP



If you have access to a SMTP server, you can send email using the smtplib module of Python. This will work on any platform, *nix or Windows.

For the SMTP server, you should use the server provide for you by your web host or ISP. If a SMTP server is running on the same machine where you are executing this script, you can simply use 'localhost'.

Note that the SMTP AUTH options first became available in Python 2.2. If you are using a version older than Python 2.2, you will not be able to use this feature of the script.

Note that when using the smtplib module to send email, you must specify the RECIPIENTS and the SENDER separately from the text of the email message. RECIPIENTS must be a Python list. SENDER is a string.

Code: Python

import smtplib
 
  smtpserver = 'mail.g4e.com'
  AUTHREQUIRED = 0 # if you need to use SMTP AUTH set to 1
  smtpuser = ''  # for SMTP AUTH, set SMTP username here
  smtppass = ''  # for SMTP AUTH, set SMTP password here
 
  RECIPIENTS = ['shabbir@g4e.com']
  SENDER = 'pradeep@g4e.com'
  mssg = open('mssg.txt', 'r').read()
 
  session = smtplib.SMTP(smtpserver)
  if AUTHREQUIRED:
      session.login(smtpuser, smtppass)
  smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)
 
  if smtpresult:
      errstr = ""
      for recip in smtpresult.keys():
          errstr = """Could not delivery mail to: %s
 
  Server said: %s
  %s
 
  %s"
"" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr)
      raise smtplib.SMTPException, errstr

If you wish to send the email to multiple recipients, then you would set the RECIPIENTS variable to something like:

Code: Python

RECIPIENTS = ['user1@g4e.com', 'user2@g4e.com', 'user3@g4e.com']

It is not necessary when using the smtplib module to include the email address in the TO or CC email headers. The smtplib module determines the recipients from the recipient list passed to the smtplib.sendmail() function. If an email address in the recipient list is not included in the email headers, thend effectively a BCC copy of the email is sent to that recipient.

shabbir 1Dec2007 17:57

Re: Sending Email With Python
 
I have reported the article for Nominate your favorite article of the month for November 2007. Add your nominations as well.


All times are GMT +5.5. The time now is 14:00.