Created
May 22, 2017 15:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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