与Python一起在电子邮件主体中查找链接



我当前正在从事Python的一个项目,该项目将连接到电子邮件服务器并查看最新电子邮件,以告诉用户电子邮件中是否有附件或链接嵌入电子邮件中的链接。我有以前的工作,但没有后者。

我可能会遇到脚本的任何((部分。当我测试时似乎一半工作。尽管这可能是由于如何打印了电子邮件字符串?

这是我连接到gmail然后查找链接的代码。

import imaplib
import email
word = ["http://", "https://", "www.", ".com", ".co.uk"] #list of strings to search for in email body
#connection to the email server
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('email@gmail.com', 'password')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("Inbox", readonly=True) # connect to inbox.
result, data = mail.uid('search', None, "ALL") # search and return uids instead
ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_uid = data[0].split()[-1]
result, data = mail.uid('fetch', latest_email_uid, '(RFC822)') # fetch the email headers and body (RFC822) for the given ID

raw_email = data[0][1] # here's the body, which is raw headers and html and body of the whole email
# including headers and alternate payloads
print "---------------------------------------------------------"
print "Are there links in the email?"
print "---------------------------------------------------------"
msg = email.message_from_string(raw_email)
for part in msg.walk():
    # each part is a either non-multipart, or another multipart message
    # that contains further parts... Message is organized like a tree
    if part.get_content_type() == 'text/plain':
        plain_text = part.get_payload()
        print plain_text # prints the raw text
        if any(word in plain_text for word in word):
            print '****'
            print 'found link in email body'
            print '****'
        else:
            print '****'
            print 'no link in email body'
            print '****'

基本上,您可以看到我有一个称为" word"的变量,其中包含在纯文本电子邮件中搜索的一系列关键字。

当我发送带有嵌入式链接的测试电子邮件时,该链接的格式为'http://'或'https://' - 电子邮件将电子邮件主体打印出来的链接,如以下文本 -

---------------------------------------------------------
Are there links in the email?
---------------------------------------------------------
Test Link <http://www.google.com/>

****
found link in email body
****

我收到我的打印消息,说"在电子邮件正文中找到链接" - 这是我在测试阶段寻找的结果,但这会导致最终程序中发生的其他事情。

但是,如果我在电子邮件中添加了一个嵌入式链接而没有http://,例如google.com,那么即使我有一个嵌入式链接,该链接也不会打印出来,也不会得到结果。

有原因吗?我还怀疑我的((循环并不是最好的。当我最初添加它时,我并不真正了解它,但它适用于http://links。然后,我只尝试了一个.com并遇到了我的问题,我在找不到解决方案时遇到的问题。

要检查电子邮件是否有附件,您可以搜索标题上的内容类型,并查看是否说"multipart/*"。带有多部分内容类型的电子邮件 May 包含附件。

要检查文本是否有链接,图像等,您可以尝试使用正则表达式。事实上,我认为这可能是您最好的选择。使用Regex(或正则表达式(,您可以找到与给定模式相匹配的字符串。例如,模式"<a[^>]+href="(.*?)"[^>]*>(.*)?</a>"应匹配电子邮件消息中的所有链接,无论它们是单个单词还是完整的URL。我希望有帮助!这是如何在Python中实现此功能的一个示例:

import re
text = "This is your e-mail body. It contains a link to <a 
href='http//www.google.com'>Google</a>."
link_pattern = re.compile('<a[^>]+href='(.*?)'[^>]*>(.*)?</a>')
search = link_pattern.search(text)
if search is not None:
    print("Link found! -> " + search.group(0))
else:
    print("No links were found.")

对于"最终用户",该链接将仅显示为" Google",而无需www,而少于http(s(...但是,源代码将具有HTML包装,因此,通过检查原始身体您可以找到所有链接的消息。

我的代码不是完美的,但我希望它能为您提供一个一般的方向...您可以在电子邮件的身体文本中浏览多种图案,以获取图像出现,视频等。要了解正则表达式,需要进行一些研究,这是Wikipedia

的另一个链接

最新更新