使用Python IMAP获取发件人电子邮件地址 [英] Get sender email address with Python IMAP

查看:149
本文介绍了使用Python IMAP获取发件人电子邮件地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个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:

示例:

Souleiman Benhida <souleb@gmail.com>

我如何才能提取电子邮件地址( souleb@gmail.com )

How can i just extract the email address (souleb@gmail.com)

我以前在PHP中这样做:

I did this before, in PHP:

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

但是,在python中,我只能获得带有地址的全名,如何单独获得地址?我目前使用这个:

But, in python I can only get the full name w/address, how can I get the address alone? 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']

谢谢!

推荐答案

使用

email.utils.parseaddr(地址)

将地址(应为某些包含地址的字段(例如To或Cc)的值)解析为其组成的真实姓名和电子邮件地址部分.返回该信息的元组,除非解析失败,在这种情况下,将返回2元组('',``).

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.

注意:最初引用为 rfc822 ,现在已弃用.

Note: originally referenced rfc822, which is now deprecated.

这篇关于使用Python IMAP获取发件人电子邮件地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆