Python: How can I change the "to" field in smtp/MIME script rather than adding a new one?
Here's an excerpt from the code I'm using. I'm looping through the part that adds the email; my problem is rather than changing the "to" field on each loop, it is appending the "to" data. Obviously this causes some issues, since the to field ends up getting longer an开发者_如何学运维d longer. I tried msgRoot.del_param('To') to no avail. I even tried setting the msgRoot['To'] to refer to the first index of a list so I could simply change the value of that list item (also didn't work).
from email.MIMEMultipart import MIMEMultipart
msgRoot = MIMEMultipart('related')
msgRoot['To'] = 'email@email.com'
You can use the replace_header
method.
replace_header(_name, _value)
Replace a header. Replace the first header found in the message that matches _name, retaining header order and field name case. If no matching header was found, a KeyError is raised.
New in version 2.2.2.
For example,
if msgRoot.has_key('to'):
msgRoot.replace_header('to', someAdress)
else:
msgRoot['to'] = 'email@email.com'
I just do this:
del msgRoot["To"]
msgRoot["To"] = "email@email.com"
My homebrewed blog platform at http://www.royalbarrel.com/ stores its blog posts this way, using Mime messages. Works great. And if someone adds a comment I upgrade the message to MimeMultipart and have the first payload be the actual blog post and subsequent payloads be the comments.
精彩评论