Skip to content

Instantly share code, notes, and snippets.

@m-rousse
Created May 22, 2017 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m-rousse/89a4128edaa52d6e227221d47e017d1e to your computer and use it in GitHub Desktop.
Save m-rousse/89a4128edaa52d6e227221d47e017d1e to your computer and use it in GitHub Desktop.
Script to rewrite links in e-mails, to be used with Sieve
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import email
import email.encoders
import sys
from bs4 import BeautifulSoup
import re
import requests
mail = sys.stdin.read()
msg = email.message_from_string(mail)
body = msg.get_payload(1)
soup = BeautifulSoup(body.get_payload(decode=True), "html.parser")
message = str(soup)
regex = r"\"(http:\/\/[\w\d\.-]+(\/track)?\/(click|open|unsubscribe)[\w\.&\/\?=\d;]+)\""
liens = re.finditer(regex, soup.__str__())
for a,b in enumerate(liens):
url = b.group(1)
kind = b.group(3)
if kind == "click":
newurl = requests.head(url)
newurl = newurl.headers['Location']
else:
newurl = "http://google.fr"
message = message.replace(url,newurl)
msg.get_payload(1).set_payload(message.encode('utf-8'))
mail = msg.as_string(unixfrom=True)
mail = mail[mail.find('\n')+1:]
print(mail)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment