Dec 26, 2021 06:55 PM
(This post was last modified: Dec 26, 2021 08:10 PM by splinter1.)
I got an exe that enables secure apps on gmail, now i need to export all mail adresses from gmail account, i found this code python 3
import email
import imaplib
import getpass
import sys
import re
from pprint import pprint as pp
# User may want to change these parameters if running script as-is
SEARCH_FOLDER = '[Gmail]Trash' # TODO: A user will want to change this
# Other folders: "INBOX", "[Gmail]/All Mail"
DEFAULT_MAIL_SERVER = 'imap.gmail.com'
# No user parameters below this line
ADDR_PATTERN = re.compile('<(.*?)>') # Finds email as <[email protected]>
def connect(user, pwd, server=DEFAULT_MAIL_SERVER):
"""Connect to [the specified] mail server. Return an open connection"""
conn = imaplib.IMAP4_SSL(server)
try:
conn.login(user, pwd)
except imaplib.IMAP4.error:
print "Failed to login"
sys.exit(1)
return conn
def print_folders(conn):
"""Print a list of open mailbox folders"""
for f in conn.list():
print "\t", f
def get_folder(conn, folder_name):
"""Fetch a specific folder (or label) from server"""
if conn.state == "SELECTED":
# Explicitly close any previously opened folders; may not be necessary
conn.close()
rv, data = conn.select(folder_name)
if rv != 'OK':
print "Could not open specified folder. Known labels:"
print_folders(conn)
return conn
def get_email_ids(conn, query='ALL'):
"""Get the numeric IDs for all emails in a given folder"""
if conn.state != "SELECTED":
raise imaplib.IMAP4.error("Cannot search without selecting a folder")
rv, data = conn.uid('search', None, query)
if rv != 'OK':
print "Could not fetch email ids" # for some reason...
return []
return data[0].split()
def fetch_message(conn, msg_uid ):
"""
Fetch a specific message uid (not sequential id!) from the given folder;
return the parsed message. User must ensure that specified
message ID exists in that folder.
"""
# TODO: Could we fetch just the envelope of the response to save bandwidth?
rv, data = conn.uid('fetch', msg_uid, "(RFC822)")
if rv != 'OK':
print "ERROR fetching message #", msg_uid
return {}
return email.message_from_string(data[0][1]) # dict-like object
def get_recipients(msg_parsed):
"""Given a parsed message, extract and return recipient list"""
recipients = []
addr_fields = ['From', 'To', 'Cc', 'Bcc']
for f in addr_fields:
rfield = msg_parsed.get(f, "") # Empty string if field not present
rlist = re.findall(ADDR_PATTERN, rfield)
recipients.extend(rlist)
return recipients
if_name_ == "__main__":
username = raw_input("Full email address: ")
password = getpass.getpass()
# Connect
mail_conn = connect(username, password)
# Open a specific folder and get list of email message uids
mail_conn = get_folder(mail_conn, SEARCH_FOLDER)
msg_uid_list = get_email_ids(mail_conn)
# Fetch a list of recipients
all_recipients = []
for msg_uid in msg_uid_list:
msg = fetch_message(mail_conn, msg_uid)
recip_list = get_recipients(msg)
all_recipients.extend(recip_list)
# Very unsophisticated way of showing the recipient list
print "List of all recipients:"
print "------------"
pp(all_recipients)
print "\n\n List of all UNIQUE recipients:"
print "-------------------------------"
pp(set(all_recipients))
try:
mail_conn.close() # Close currently selected folder (if any)
finally:
mail_conn.logout()
but it returns "failed to login" ,
anyone knows a working code? help is appriciated. Since when does this not work anymore?
To The Krays:
Also The Krays, what happened? My messages on telegram won;t arive, like you are offline. our hole chat has been deleted to.
\
Nevermind, i got it to work
Update,\
somehow it works for one gmail account, but it doesnt for my other gmail account, both ave secure apps enabled. How can this be?
import email
import imaplib
import getpass
import sys
import re
from pprint import pprint as pp
# User may want to change these parameters if running script as-is
SEARCH_FOLDER = '[Gmail]Trash' # TODO: A user will want to change this
# Other folders: "INBOX", "[Gmail]/All Mail"
DEFAULT_MAIL_SERVER = 'imap.gmail.com'
# No user parameters below this line
ADDR_PATTERN = re.compile('<(.*?)>') # Finds email as <[email protected]>
def connect(user, pwd, server=DEFAULT_MAIL_SERVER):
"""Connect to [the specified] mail server. Return an open connection"""
conn = imaplib.IMAP4_SSL(server)
try:
conn.login(user, pwd)
except imaplib.IMAP4.error:
print "Failed to login"
sys.exit(1)
return conn
def print_folders(conn):
"""Print a list of open mailbox folders"""
for f in conn.list():
print "\t", f
def get_folder(conn, folder_name):
"""Fetch a specific folder (or label) from server"""
if conn.state == "SELECTED":
# Explicitly close any previously opened folders; may not be necessary
conn.close()
rv, data = conn.select(folder_name)
if rv != 'OK':
print "Could not open specified folder. Known labels:"
print_folders(conn)
return conn
def get_email_ids(conn, query='ALL'):
"""Get the numeric IDs for all emails in a given folder"""
if conn.state != "SELECTED":
raise imaplib.IMAP4.error("Cannot search without selecting a folder")
rv, data = conn.uid('search', None, query)
if rv != 'OK':
print "Could not fetch email ids" # for some reason...
return []
return data[0].split()
def fetch_message(conn, msg_uid ):
"""
Fetch a specific message uid (not sequential id!) from the given folder;
return the parsed message. User must ensure that specified
message ID exists in that folder.
"""
# TODO: Could we fetch just the envelope of the response to save bandwidth?
rv, data = conn.uid('fetch', msg_uid, "(RFC822)")
if rv != 'OK':
print "ERROR fetching message #", msg_uid
return {}
return email.message_from_string(data[0][1]) # dict-like object
def get_recipients(msg_parsed):
"""Given a parsed message, extract and return recipient list"""
recipients = []
addr_fields = ['From', 'To', 'Cc', 'Bcc']
for f in addr_fields:
rfield = msg_parsed.get(f, "") # Empty string if field not present
rlist = re.findall(ADDR_PATTERN, rfield)
recipients.extend(rlist)
return recipients
if_name_ == "__main__":
username = raw_input("Full email address: ")
password = getpass.getpass()
# Connect
mail_conn = connect(username, password)
# Open a specific folder and get list of email message uids
mail_conn = get_folder(mail_conn, SEARCH_FOLDER)
msg_uid_list = get_email_ids(mail_conn)
# Fetch a list of recipients
all_recipients = []
for msg_uid in msg_uid_list:
msg = fetch_message(mail_conn, msg_uid)
recip_list = get_recipients(msg)
all_recipients.extend(recip_list)
# Very unsophisticated way of showing the recipient list
print "List of all recipients:"
print "------------"
pp(all_recipients)
print "\n\n List of all UNIQUE recipients:"
print "-------------------------------"
pp(set(all_recipients))
try:
mail_conn.close() # Close currently selected folder (if any)
finally:
mail_conn.logout()
but it returns "failed to login" ,
anyone knows a working code? help is appriciated. Since when does this not work anymore?
To The Krays:
Also The Krays, what happened? My messages on telegram won;t arive, like you are offline. our hole chat has been deleted to.
\
Nevermind, i got it to work
Update,\
somehow it works for one gmail account, but it doesnt for my other gmail account, both ave secure apps enabled. How can this be?

