sending emails to a list of recipients [update]

Tim Roberts timr at probo.com
Mon Mar 27 04:03:40 EST 2006


Kun <neurogasm at gmail.com> wrote:
>
>Kun wrote:
>> i have the following code:
>> 
>> ----------------------------------
>> import smtplib
>> 
>> from email.MIMEText import MIMEText
>> fp = open('confirmation.txt', 'rb')
>> msg = MIMEText(fp.read())
>> 
>>  From = 'xxxx at xxxx.xxxx.edu'
>> 
>> msg['Subject'] = 'Purchase Confirmation'
>> msg ['From'] = From
>> msg['To'] = emails
>> 
>> s = smtplib.SMTP('xxxx.xxx.xxx.edu')
>> s.login('xxxxx','xxxx')
>> s.sendmail(msg['From'], msg['To'], msg.as_string())
>> s.close()
>> ----------------------------------
>
>this is my error msg of leaving the code in its current state... (brave 
>yourself)
>
>Traceback (most recent call last):
>   File "/Tutorial/IMAP/scannermailer.py", line 41, in -toplevel-
>     s.sendmail(msg['From'], msg['To'], msg.as_string())
>   File 
>"/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/Message.py", 
>line 129, in as_string
>     g.flatten(self, unixfrom=unixfrom)
>...
>   File 
>"/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/email/quopriMIME.py", 
>line 79, in _max_append
>     L.append(s.lstrip())
>AttributeError: 'list' object has no attribute 'lstrip'

OK, I see what's going on now.  The problem is that SMTP.sendmail and
email.MIMEText need two different things.

email.MIMEText sets up the "To:" header for the body of the e-mail.  It is
ONLY used for displaying a result to the human being at the other end, and
like all e-mail headers, must be a single string.  (Note that it does not
actually have to have anything to do with the people who actually receive
the message.)

SMTP.sendmail, on the other hand, sets up the "envelope" of the message for
the SMTP protocol.  It needs a Python list of strings, each of which has a
single address.

So, what you need to do is COMBINE the two replies you received.  Set
msg['To'] to a single string, but pass the raw list to sendmail:

    msg['To'] = ', '.join( emails )
    ....
    s.sendmail( msg['From'], emails, msg.as_string() )
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list