How to send email from a Python script

Today I needed to send email from a Python script. As always I searched Google and found the following script that fits to my need.

import smtplib

SERVER = "localhost"

FROM = "sender@example.com"
TO = ["user@example.com"] # must be a list

SUBJECT = "Hello!"

TEXT = "This message was sent with Python's smtplib."

# Prepare actual message

message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail

server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()

[Source: http://effbot.org/pyfaq/how-do-i-send-mail-from-a-python-script.htm]

But when I tried to run the program, I got the following error message:
Traceback (most recent call last):
File "email.py", line 1, in 
import smtplib
File "/usr/lib/python2.5/smtplib.py", line 46, in 
import email.Utils
File "/home/dsebd/email.py", line 24, in 
server = smtplib.SMTP(SERVER)
AttributeError: 'module' object has no attribute 'SMTP'

I got rid of the problem when I renamed the file email.py to another file!

Can anyone explain the reason?

Update [21 August 2011]
If you want to use it as function you can use the following code:

import smtplib

def send_email(sender, receiver, subject, body):
    msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" 
        %(sender, receiver, subject, body))
    s = smtplib.SMTP('localhost')
    s.sendmail(sender, [receiver], msg)
    s.quit()
You should also check this link for more examples (won't work in older version of python like 2.4.x): http://docs.python.org/library/email-examples.html

Comments

Casey said…
The problem is related to the fact that your local 'email.py' file is being found in the search path before the system package 'email'.

The error message you were given is a stack trace:

1)File "email.py", line 1, in
import smtplib

python is trying load smtplib from the 1st line of your file

2) File "/usr/lib/python2.5/smtplib.py", line 46, in
import email.Utils

python found "smtplib" and is trying to initialize it. On line 46 there is an "import" command to load 'email.Utils' module

3) File "/home/dsebd/email.py", line 24, in
server = smtplib.SMTP(SERVER)
AttributeError: 'module' object has no attribute 'SMTP'

This is the ERROR. Python has started to recursively load your 'email.py' file in the current working directory because it does not realize that it is in the process of loading it from step 1. This is because when you run email.py for the first time, it is loaded with the name '__main__'. So the reference to import 'email.Utils' cause python to realize it needs to figure out where 'email' is. Python finds a match in the current directory before looking in /usr/lib/python2.5/, where the REAL 'email' package is stored.

After finding your local 'email.py' file, python tries to initialize it. It gets past the 'import smtplib' statement this time, because a local reference was made once it found it the first time around. (Note: the system is still in the process of loading smtplib, and has not yet completed. read up on circular python import statements for more info) After getting past the "import smtplib', the execution finally dies at the reference to smtplib.SMTP. This is because (as noted above) the smtplib import statement has not yet completed yet, and does not have the internal reference to 'SMTP' yet.

Solution:

By renaming your email.py file in your working directory, you remove the naming conflict and it finds the correct package.
Tamim Shahriar said…
Thanks for your explanation.
Unknown said…
What is the
>>>messsage = """\

doing? Thanks.
Tamim Shahriar said…
jp, as I broke the the string into multiple lines, it had to be used.
Muhamed Niyas C said…
Hi Casey,
i got the same error and Your post helped me to fix the issue. Thanks a lot

Niyas
Unknown said…
hello guys! i am having this problem:

"""
# Error: (10061, 'Connection refused')
"""

how do i fix it? could u help me?
thanks in advance!
Ketki said…
I have a similar requirement.
I am trying to send an email using a python script.The email will in turn have a hyperlink to open another email with subject and body populate.The sender will just have to populate the "To" field and send the email.
I am able to create the hyperlink, but the hyperlink is showing all the coding behind -
It looks like this -
mailto:?cc=pendingticketreminders%40warnerbros.com&Subject=Reminder%201%20for%20Incident%3A%20INC000000671053&Body=Incident%20details%3A%0A%0A%20%20%20%20Incident%20ID%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3D%3D%3D%3E%20INC000000671053%0A%20%20%20%20Reminder%20Status%20%20%20%20%20%20%20%20%20%3D%3D%3D%3E%20No%20Follow%20Up%20Done%0A%20%20%20%20Assigned%20Group%20%20%20%20%20%20%20%20%20%20%3D%3D%3D%3E%20WBEI.BDS.MARVIN%20Front%20End%0A%20%20%20%20Assignee%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3D%3D%3D%3E%20Pavan%20Kumar%0A%20%20%20%20Time%20of%20Pending%20%20%20%20%20%20%20%20%20%20%3D%3D%3D%3E%201/8/10%203%3A09%3A20%20AM%0A%20%20%20%20Pending%20Age%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3D%3D%3D%3E%205

Is there a way to rename this hyperlink so that the code is hidden?
Lopes said…
Thank you!
I got the same problem and now I know why it occurs and how to avoid this.
:-)

José Lopes
joselopes.org
Anonymous said…
I am trying to send an email to a Gmail account, and it never arrives. Sending it to other accounts doesn't have problems, but Gmail doesn't work. Doesn't even show up in spam. Anyone else have this problem? What do I do?
JPhenow said…
This helped quite a bit, however I would suggest simply doing:
""" % ( FROM, ", " + TO, SUBJECT, TEXT )

Because otherwise you get a long list of emails because python turns that string into an array of chars which can cause some problems.

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code