[Tutor] Simple Question (I Hope)

Steven D'Aprano steve at pearwood.info
Sun Jan 15 04:44:17 CET 2012


Chris Kavanagh wrote:

> 16 msg['Subject'] = 'The contents of %s' % textfile
> 17 msg['From'] = me
> 18 msg['To'] = you

> What I don't understand is lines 16-18, more specifically the 
> msg['Subject'] format. I thought this was only done with dics?? 
> Obviously the variable msg isn't a dic, so how can this be done??

It works with anything that behaves like a mapping. That includes dicts, 
naturally, but also collections.OrderedDict and any other type of object that 
supports the special __getitem__ method. This includes MIMEText objects, which 
are designed to act like mappings when you set email headers:


py> from email.mime.text import MIMEText
py> msg = MIMEText('This is the body of your email')
py> print(msg)
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

This is the body of your email
py>
py>
py> msg['X-Header'] = 'Nobody expects the Spanish Inquisition!'
py> print(msg)
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
X-Header: Nobody expects the Spanish Inquisition!

This is the body of your email
py>
py>


-- 
Steven



More information about the Tutor mailing list