[lug] python script to send email via SMTP

Michael J. Hammel mjhammel at graphics-muse.org
Tue Jul 17 11:21:20 MDT 2007


I found the following script online.  I haven't learned Python yet, so I
can't tell if it should work or not, but it seems to at least try to
work.  The problem is I get the following traceback when it's run:

Traceback (most recent call last):
  File "./mail.py", line 20, in ?
    session.login(smtpuser, smtppass)
  File "/usr/lib/python2.4/smtplib.py", line 587, in login
    raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, 'Error: authentication failed')

Should this work?  Have I just forgotten my SMTP password?  I'm just
trying to send email from the command line (like via cron jobs) without
having to set up sendmail (for which I have no clue how to do SMTP login
authentication stuff).  If there is another way - bash, perl, or C
preferred - I'm all ears.

#!/usr/bin/env python
#
#  Sending mail using python
#-----------------------------------------------------------
import smtplib

smtpserver = 'myserver.com'
AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1
smtpuser = 'userid at myserver.com'  # for SMTP AUTH, set SMTP username
here
smtppass = 'xxx'  # for SMTP AUTH, set SMTP password here

RECIPIENTS = ['person at place.com']
SENDER = 'sender at otherplace.com'
mssg = open('msg.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

-- 
Michael J. Hammel                                    Senior Software Engineer
mjhammel at graphics-muse.org                           http://graphics-muse.org
------------------------------------------------------------------------------
I might be a butterfly, dreaming I'm a man writing down my thoughts. - 
     Unknown, paraphrased from Taoist philosopher Chuang Tzu




More information about the LUG mailing list