📜  Python|从特定用户处获取您的 gmail 电子邮件

📅  最后修改于: 2022-05-13 01:54:25.697000             🧑  作者: Mango

Python|从特定用户处获取您的 gmail 电子邮件

如果您想知道我们如何使用Python获取 Gmail 电子邮件,那么本文适合您。
众所周知, Python是一种多用途语言,可用于执行各种任务。获取 Gmail 电子邮件虽然是一项繁琐的任务,但使用Python,如果您精通它的用法,可以完成很多事情。 Gmail 为希望在不手动登录浏览器的情况下访问 Gmail 的客户提供 IMAP 访问。

在设置页面中,在运行脚本之前启用它。

执行:
此实现中使用的库包括imaplibemail 。您必须通过进入您的 Gmail 帐户设置来手动启用 IMAP 访问。在此之后,您无需登录浏览器即可访问您的 Gmail 帐户。

  • 实现中定义了三个函数,用于获取电子邮件正文、搜索来自特定用户的电子邮件以及获取标签下的所有电子邮件。
  • 为了显示结果,我从另一个 Gmail 帐户向我的 ID 发送了电子邮件。现在我将从我的 Gmail 帐户中获取电子邮件,这些电子邮件是从我的另一个 Gmail 帐户收到的。
  • 该过程从在imaplib 库的帮助下建立 Gmail 连接并向其证明我们的 Gmail 登录凭据开始。
  • 登录后,我们在标签下选择电子邮件:收件箱,这是所有用户的默认标签部分。但是,您也可以创建自己的标签。
  • 然后我们调用 get emails函数并提供搜索函数结果中的参数,即“来自用户”
  • 在获取电子邮件函数中,我们将所有电子邮件放入名为“msgs”的数组中
  • 现在打印以查看 msgs 数组
  • 现在我们可以轻松地遍历这个数组。我们按照电子邮件到达的顺序对其进行迭代。然后我们正在搜索我们的内容开始的索引。对于不同的电子邮件/用户,此索引部分将有所不同,用户可以手动更改索引以仅打印他们需要的部分。
  • 我们将结果打印出来。

下面是Python的实现——

Python3
# Importing libraries
import imaplib, email
 
user = 'USER_EMAIL_ADDRESS'
password = 'USER_PASSWORD'
imap_url = 'imap.gmail.com'
 
# Function to get email content part i.e its body part
def get_body(msg):
    if msg.is_multipart():
        return get_body(msg.get_payload(0))
    else:
        return msg.get_payload(None, True)
 
# Function to search for a key value pair
def search(key, value, con):
    result, data = con.search(None, key, '"{}"'.format(value))
    return data
 
# Function to get the list of emails under this label
def get_emails(result_bytes):
    msgs = [] # all the email data are pushed inside an array
    for num in result_bytes[0].split():
        typ, data = con.fetch(num, '(RFC822)')
        msgs.append(data)
 
    return msgs
 
# this is done to make SSL connection with GMAIL
con = imaplib.IMAP4_SSL(imap_url)
 
# logging the user in
con.login(user, password)
 
# calling function to check for email under this label
con.select('Inbox')
 
 # fetching emails from this user "tu**h*****1@gmail.com"
msgs = get_emails(search('FROM', 'MY_ANOTHER_GMAIL_ADDRESS', con))
 
# Uncomment this to see what actually comes as data
# print(msgs)
 
 
# Finding the required content from our msgs
# User can make custom changes in this part to
# fetch the required content he / she needs
 
# printing them by the order they are displayed in your gmail
for msg in msgs[::-1]:
    for sent in msg:
        if type(sent) is tuple:
 
            # encoding set as utf-8
            content = str(sent[1], 'utf-8')
            data = str(content)
 
            # Handling errors related to unicodenecode
            try:
                indexstart = data.find("ltr")
                data2 = data[indexstart + 5: len(data)]
                indexend = data2.find("
")                   # printtng the required content which we need                 # to extract from our email i.e our body                 print(data2[0: indexend])               except UnicodeEncodeError as e:                 pass


输出: