0

I am trying to send an email using the python smtp library.Everything seems to work fine but i am getting the last attachment repeated, while trying to send two attachments i got three with the last repeated .I am trying to figure out this but couldn't.Here is my code snippet for the message composing function:

def create_email_message(sender_address, recipient_address, subject, body, filesin=[]):
    '''
    Creates a ready to go email message along with the headers.
    @param: filesin
            A list of tuples. Example:
            [(file1_name,file1_data),(file2_name,file2_data),.......]
    '''

    msg = MIMEMultipart('alternative')
    msg['Subject'] = "%s" % Header(subject, 'utf-8')
    msg['From'] = sender_address
    msg['To'] = recipient_address

    htmlpart = MIMEText(body, 'html', 'UTF-8')
    msg.attach(htmlpart)


    for file_obj in filesin:
        data = file_obj[1]
        name = file_obj[0]
        attach_obj = MIMEBase("application", "octet-stream")
        attach_obj.set_payload(data)
        Encoders.encode_base64(attach_obj)
        attach_obj.add_header('Content-Disposition', 'attachment',
                              filename=name)
        msg.attach(attach_obj)

    return msg.as_string() 

The filesin parameter is a tuple as illustrated in the function definition.The strangest part is that when i view the original email ,then gmail only show two Content Disposition headers.Can't figure out why the last attachment is repeating.

Regards.

darxtrix
  • 2,032
  • 2
  • 23
  • 30
  • Not sure it's the cause of your problem but you may want to fix how you define the default for `filesin`, cf http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument – bruno desthuilliers Dec 19 '13 at 12:23
  • Since i am passing the value of filesin by myself; i guess the good link you shared is not in picture here.But,thanks for the nice stuff. – darxtrix Dec 19 '13 at 12:35
  • How can you generate `filesin` variable? Can you paste it here? – Syed Habib M Dec 19 '13 at 12:52
  • I fail to spot any obvious error in your code snippet (except for the already mentionned default value for `filesin`). – bruno desthuilliers Dec 19 '13 at 12:55
  • Finally i changed: msg=MIMEMultipart("alternative") to msg=MIMEMultipart() only and the error got fixed but why? – darxtrix Dec 19 '13 at 13:15
  • Well the filesin was like that: [("mmm1.txt",open("D:\\mmm1.txt").read()),("mmm2.txt",open("D:\\mmm2.txt").read())] – darxtrix Dec 19 '13 at 13:17

0 Answers0