1
votes

I am trying to add string value to subject field while sending email using smtplib, but unfortunately, msg['Subject'] always throws the error:

TypeError: 'str' object does not support item assignment

Below is my code:

    for host in self.hostnames:
        for h in host:
            start = 'Create'
            s = str(h)
            l = str(self.lease)
            u = str(self.username)
            f = str(listFlavor)
            subject = start + ' ' + s + ' ' + l + ' ' + u + ' ' + f

            msg            = 'Add Lease days of %s' % str(self.lease)
            msg['Subject'] = subject
            msg['From']    = self.username
            msg['To']      = '[email protected]'

            s = smtplib.SMTP('test.test.com')
            s.sendmail('[email protected]', self.username, msg.as_string())
            s.quit()
1
msg is a string. What do you expect msg['Subject'] = subject to do? - PM 2Ring

1 Answers

2
votes

yes that's true.

I have added this line to initially declare msg.

msg = MIMEMultipart('related')

which is a dict and holds the values added to msg.