1. 程式人生 > >修改python原文件中的from、to字段

修改python原文件中的from、to字段

python email from to

1down votefavorite

1

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 and 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 protected]



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 protected]


Thank you, that worked perfectly! – Dan Apr 24 ‘11 at 14:26




in Python 3.5 I had to use if ‘to‘ in message: because has_key has been deprecated. – Tom SitterJun 8 ‘16 at 21:17



Python 3 changed dict syntax. See docs.python.org/3/whatsnew/3.0.html#builtins "Removed. dict.has_key() – use the in operator instead." – gimel Jun 9 ‘16 at 5:31


原文:

https://stackoverflow.com/questions/5770951/python-how-can-i-change-the-to-field-in-smtp-mime-script-rather-than-adding-a

修改python原文件中的from、to字段