python - 使用 Python 查找电子邮件正文中的链接

标签 python email parsing imaplib

我目前正在使用 Python 开发一个项目,该项目将连接到电子邮件服务器并查看最新的电子邮件,以告诉用户电子邮件中是否嵌入了附件或链接。我可以使用前者,但不能使用后者。

我的脚本的 if any() 部分可能遇到问题。因为当我测试时它似乎工作了一半。虽然这可能是由于电子邮件字符串的打印方式所致?

这是我连接到 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),则该链接不会打印出来,并且我不会得到结果,即使我有嵌入链接也是如此。

这有什么原因吗?我还怀疑我的 if any() 循环可能并不是最好的。当我最初添加它时我并没有真正理解它,但它适用于 http://链接。然后我尝试了 .com,但遇到了我无法找到解决方案的问题。

最佳答案

要检查电子邮件是否有附件,您可以搜索标题中的 Content-Type,看看是否显示 "multipart/*" 。具有多部分内容类型的电子邮件可能包含附件。

要检查文本中的链接、图像等,您可以尝试使用 Regular Expressions 。事实上,我认为这可能是您最好的选择。使用正则表达式(或正则表达式),您可以找到与给定模式匹配的字符串。图案"<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 对其进行包装,因此通过检查原始正文您可以找到该消息的所有链接。

我的代码并不完美,但我希望它能为您提供一个总体方向...您可以在电子邮件正文中查找多个模式,以查找图像出现、视频等。要学习正则表达式,您将需要研究一下,这是另一个 link, to Wikipedia

关于python - 使用 Python 查找电子邮件正文中的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48985722/

相关文章:

python - 如何正确构建自引用 SQLalchemy 邻接列表混合

python - 为什么我们说 Keras 中的函数式 API 用于非顺序模型?

java - 从 Jar 文件在 linux 中发送电子邮件

java - 如何从 Java 发送 html 电子邮件到 outlook

java - 解析最初使用 Jackson 和 Jackson 解析器编码的 JSON 字符串会抛出 IOExeption

python - Django 可以与 pandas 和 numpy 一起很好地工作吗?

python - Tumblr API 博客方法返回 401 "Not Authorized",但用户方法完美无缺

email -/etc/aliases 使用管道运行脚本返回错误 (mailer=prog, dsn=5.3.0, stat=unknown mailer error 2)

jQuery if then else 使用 URL 解析器插件,一定有一个更优雅的解决方案

sql - HugSQL错误: column "date_answer" is of type date but expression is of type character varying?