从逗号分隔的电子邮件ID列表中删除变量

时间:2013-10-16 22:25:49

标签: python

我有以下用于发送电子邮件的子例程,我试图从变量“to”中删除用户“username1”,这是一个逗号分隔的电子邮件ID',我正在使用to = to.strip('username1 ')似乎不起作用,任何想法如何从变量“to”删除username1@company.com

def email (body,subject,to=None):
    msg = MIMEText("%s" % body)
    msg["Content-Type"] = "text/html"
    msg["From"] = "serviceaccount@company.com"
    if to!=None:
        to=to.strip()
        to=to.strip('username1@company.com')
        msg["To"] = to
        print to

2 个答案:

答案 0 :(得分:0)

用逗号分隔它,然后用逗号连接它们,减去被排除的一个......

msg['To'] = ','.join(email for email in msg['To'].split(',') if email != 'username1@company.com')

您也可以将其概括为“不要邮件”列表,例如:

DO_NOT_MAIL = ['username1@companyname.com', 'username2@anothercompany.com']

def email(body, subject, to=None):
    msg = MIMEText("%s" % body)
    msg["Content-Type"] = "text/html"
    msg["From"] = "serviceaccount@company.com"
    msg["To"] = ', '.join(email for email in set(to).difference(DO_NOT_MAIL))

答案 1 :(得分:0)

您可以将它们拆分为列表,然后从列表中删除不需要的电子邮件:

exclude='username@company.com'
to=to.split(',')
to.remove(exclude)
to=','.join(to)

如果exclude是多个地址的列表,则循环遍历列表:

....
for e in exclude: 
    to.remove(e)
...