Skip to content

Instantly share code, notes, and snippets.

@eriknelson
Created September 8, 2017 20:02
Show Gist options
  • Save eriknelson/b4c449fc267041dc70b2119b6ca7bdee to your computer and use it in GitHub Desktop.
Save eriknelson/b4c449fc267041dc70b2119b6ca7bdee to your computer and use it in GitHub Desktop.
============================================================
Checking for List-Unsubscribe headers...
============================================================
Found unsub header in msg [ 2 ] from: [ "Qatar Airways" <[email protected]> ]
List-Unsubscribe: <http://qr.qatarairways.com/pub/optout/UnsubscribeOneStepConfirmAction?YES=true&_ri_=X0Gzc2X%3DYQpglLjHJlTQGmCEwzcJNPyWAvKkzdzg4ykAoezgzdLzazbzfyg7E4NzakgzaCTzfLRzedzgt8R&_ei_=EolaGGF4SNMvxFF7KucKuWObEvbgz_lhDCu4wSJxEH3Z_JWEZp1n8F_ZWur6_mDUeaRx0KaRl21dG6NK>, <mailto:unsubscribe-YQpglLjHJlTQGmCEwzcJNPyWAvKkzdzg4ykAoezgzdLzazbzfyg7E4NzakgzaCTzfLRzedzgt8R@imh.rsys2.com?subject=List-Unsubscribe>
Found unsub header in msg [ 6 ] from: [ "Kite" <[email protected]> ]
List-Unsubscribe: <mailto:32.LJEWU5KBO5AUEWDNJIYEIMBNKZBFINLHKZVW4RTJJRGES===@unsubscribe2.customer.io>, <http://track.customer.io/unsubscribe/ZIjuAwABXmJ0D0-VBT5gVknFiLLI>
============================================================
Found 2 of 6 messages with unsubscribe headers...
#!/usr/bin/env python
import imaplib
import re
import email
# Fill in
# EMAIL_USER="XXX"
# EMAIL_PASS="XXX"
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(EMAIL_USER, EMAIL_PASS)
mail.select('[Gmail]/All Mail')
_, data = mail.search(None, 'All')
ids = data[0]
id_list = ids.split()
def list_header_check(msg):
if 'List-Unsubscribe' in msg:
if not 'From' in msg:
print 'msg [ {0} ] is missing From header'
else:
sender = msg['From']
print 'Found unsub header in msg [ {0} ] from: [ {1} ]'.format(msgid, sender)
print 'List-Unsubscribe: {0}'.format(msg['List-Unsubscribe'])
return True
return False # Not found, return false
hitcount = 0
print "============================================================"
print "Checking for List-Unsubscribe headers..."
print "============================================================"
for msgid in id_list:
_, data = mail.fetch(msgid, '(RFC822)')
raw_msg = data[0][1]
msg = email.message_from_string(raw_msg)
############################################################
# Apply all the rules to check for hit
############################################################
got_hit = list_header_check(msg)
# do another thing
############################################################
if got_hit:
print ""
hitcount += 1
print "============================================================"
print 'Found {0} of {1} messages with unsubscribe headers...'.format(hitcount, len(id_list))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment