attribute error: list object has not attribute lstrip in sending an email with attachment

19,238

Solution 1

it was a small error. receiver parameter was list type. either it should be list converted to string using join method or if it is a single recipient, then pass it as a string only

Solution 2

receiver = ['[email protected]'] This is a list but msg['To'] is expecting a string and hence the error.

You can use ','.join(receiver) and that should solve your problem.

Solution 3

This appears to be a issue from smtplib. The documentation clearly says that it accepts a list

The arguments are:
        - from_addr    : The address sending this mail.
        - **to_addrs     : A list of addresses to send this mail to.  A bare
                         string will be treated as a list with 1 address.**
        - msg          : The message to send.

Usage from documentation:

 "Example:

     >>> import smtplib
     >>> s=smtplib.SMTP("localhost")
     **>>> tolist= 
     ["[email protected]","[email protected]","[email protected]","[email protected]"]**
     >>> msg = '''\\
     ... From: [email protected]
     ... Subject: testin'...
     ...
     ... This is a test '''
     >>> s.sendmail("[email protected]",tolist,msg)"

Also as said in the documentation if recipients are passed as string, mail is being sent to first mailid only.

So actually 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:

emails = ['a.com','b.com', 'c.com']** **msg['To'] = ', '.join( emails ) .... s.sendmail( msg['From'], emails, msg.as_string() )****

Share:
19,238
POOJA GUPTA
Author by

POOJA GUPTA

Updated on July 24, 2022

Comments

  • POOJA GUPTA
    POOJA GUPTA almost 2 years

    i am attaching a file from a particular path c:\important\log.txt

    sender = '[email protected]'
    receiver = ['[email protected]']
    message = """From: From Pooja Gupta <[email protected]>
    To: To Shubha Goel <[email protected]>
    Subject: SMTP e-mail test
    
    This is a test e-mail message.
    """
    
    file_name = 'C:\important\log.txt'
    msg=MIMEMultipart()
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = message
    msg['Date'] = email.Utils.formatdate(localtime=True)
    
    # build the attachment
    att = MIMEBase('application', 'base64')
    att.set_payload(open(file_name, 'rb').read())
    email.Encoders.encode_base64(att)
    att.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_name))
    msg.attach(att)
    
    print 'successfully built attachment'
    try:
        session = smtplib.SMTP('smtp.gmail.com',587)
        print 'Starting..'
        session.ehlo()
        print 'ehlo executed..'
        session.starttls()
        print 'starttls done'
    
        session.login(sender,'snxzoumwhpybzvmo')
        print 'logged in'
        session.sendmail(sender,receiver,msg.as_string())
        print 'sendmail executed..now quitting'
        session.close()
    
    except smtplib.SMTPRecipientsRefused:
        print 'Recipient refused'
    except smtplib.SMTPAuthenticationError:
        print 'Auth error'
    except smtplib.SMTPSenderRefused:
        print 'Sender refused'
    except smtplib.SMTPException:
        print('Error')
    

    It keeps on giving me the same error of Attribute error list object has no attribute lstrip the following is the error, stack trace :

    Traceback (most recent call last):
      File "<pyshell#8>", line 1, in <module>
        execfile('C:\important\secret_file.pyw')
      File "C:\important\secret_file.pyw", line 45, in <module>
        session.sendmail(sender,receiver,msg.as_string())
      File "C:\Python27\lib\email\message.py", line 137, in as_string
        g.flatten(self, unixfrom=unixfrom)
      File "C:\Python27\lib\email\generator.py", line 83, in flatten
        self._write(msg)
      File "C:\Python27\lib\email\generator.py", line 115, in _write
        self._write_headers(msg)
      File "C:\Python27\lib\email\generator.py", line 164, in _write_headers
        v, maxlinelen=self._maxheaderlen, header_name=h).encode()
      File "C:\Python27\lib\email\header.py", line 410, in encode
        value = self._encode_chunks(newchunks, maxlinelen)
      File "C:\Python27\lib\email\header.py", line 370, in _encode_chunks
        _max_append(chunks, s, maxlinelen, extra)
      File "C:\Python27\lib\email\quoprimime.py", line 97, in _max_append
        L.append(s.lstrip())
    AttributeError: 'list' object has no attribute 'lstrip'
    

    Please Help.