Python检索电子邮件地址

时间:2016-04-18 09:30:18

标签: python email

我想创建一个Python程序,使用“email”和“smtplib”包重新发送电子邮件。

UserDict

在上述情况下,我有2个收件人,我想通过smtplib重新发送给这2个人。

 import email
 import smtplib

 f = open('email_source.eml')
 em = email.message_from_file(f)

 email_from = em['FROM']  # '"Me" <me@xyz.com>'
 email_to = em['TO']      # '"John, A" <john@abc.com>, "Peter, B" <peter@def.com>'

如果我将字符串email_to放入sendmail,它只会将电子邮件发送给第一批人。如果我用列表替换email_to,

 import smtplib

 smtp = smtplib.SMTP('localhost', '25')
 smtp.sendmail(email_from, email_to, em.as_string())

电子邮件可以发送给双方。

我的问题是,我可以将收件人从em ['TO']和em ['CC']字符串中提取到列表中吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

问题是smtp.sendmail需要一个地址列表,根据文档:

  

SMTP.sendmail(from_addr,to_addrs,msg,mail_options = [],rcpt_options = [])

     

发送邮件。所需的参数是RFC 822 from-address字符串,RFC 822 to-address字符串列表(裸字符串将被视为具有1个地址的列表)[...]

email - 包中得到一个字符串,smtp - 包然后只解释为一个地址。

简单来说,您需要将分配到 -address-string到地址列表中。

你是怎么做到的?你可以手动完成,但最好只依赖于库:

import email.utils

email_to_raw   = '"John, A" <john@abc.com>, "Peter, B" <peter@def.com>'

# split into (Name, Addr) tuple
email_to_split = email.utils.getaddresses([email_to_raw])

# combine the tuples into addresses, but keep the list
email_to = [email.utils.formataddr(pair) for pair in email_to_split]

print(email_to) # ['"John, A" <john@abc.com>', '"Peter, B" <peter@def.com>']

在API的设计者发誓之后,你将它包装成一个函数:

import email.utils

def split_combined_addresses(addresses):
    parts = email.utils.getaddresses(addresses)
    return [email.utils.formataddr(name_addr) for name_addr in parts]

print(split_combined_addresses(email_to))