简体   繁体   English

使用 Python IMAP 获取发件人电子邮件地址

[英]Get sender email address with Python IMAP

I have this python IMAP script, but my problem is that, every time I want to get the sender's email address, (From), I always get the sender's first name followed by their email address:我有这个 python IMAP 脚本,但我的问题是,每次我想获取发件人的电子邮件地址(发件人)时,我总是得到发件人的名字,然后是他们的电子邮件地址:

Example:例子:

Souleiman Benhida <souleb@gmail.com>

How can i just extract the email address ( souleb@gmail.com )我怎样才能提取电子邮件地址( souleb@gmail.com

I did this before, in PHP:我以前在 PHP 中这样做过:

    $headerinfo = imap_headerinfo($connection, $count)
    or die("Couldn't get header for message " . $count . " : " . imap_last_error());
$from = $headerinfo->fromaddress;

But, in python I can only get the full name w/address, how can I get the address alone?但是,在python中我只能得到带地址的全名,我怎么能单独得到地址呢? I currently use this:我目前使用这个:

    typ, data = M.fetch(num, '(RFC822)')
mail = email.message_from_string(data[0][1])
headers = HeaderParser().parsestr(data[0][1]) 
message = parse_message(mail)  #body
org = headers['From']

Thanks!谢谢!

Just one more step, using email.utils :再多一步,使用email.utils

email.utils.parseaddr(address)

Parse address – which should be the value of some address-containing field such as To or Cc – into its constituent realname and email address parts.将地址(应该是某些包含地址的字段(例如收件人或抄送)的值)解析为其组成的实名和电子邮件地址部分。 Returns a tuple of that information, unless the parse fails, in which case a 2-tuple of ('', '') is returned.返回该信息的元组,除非解析失败,在这种情况下返回 ('', '') 的 2 元组。

Note: originally referenced rfc822 , which is now deprecated.注意:最初引用rfc822 ,现在已弃用。

to = email.utils.parseaddr(msg['cc'])

这对我有用。

My external lib https://github.com/ikvk/imap_tools let you work with mail instead read IMAP specifications.我的外部库https://github.com/ikvk/imap_tools让您使用邮件而不是阅读 IMAP 规范。

from imap_tools import MailBox, A

# get all emails from INBOX folder
with MailBox('imap.mail.com').login('test@mail.com', 'pwd', 'INBOX') as mailbox:
    for msg in mailbox.fetch(A(all=True)):
        print(msg.date, msg.from_, msg.to, len(msg.text or msg.html))

msg.from_, msg.to - parsed addresses, like: 'Sender@ya.ru' msg.from_, msg.to - 解析地址,如:'Sender@ya.ru'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM