Skip to content

Instantly share code, notes, and snippets.

@wiesson
Last active January 4, 2019 18:58
Show Gist options
  • Save wiesson/7543123 to your computer and use it in GitHub Desktop.
Save wiesson/7543123 to your computer and use it in GitHub Desktop.
Load *.eml files from a folder Usage: python sendmails.py --start path/to/
from multiprocessing import Pool
import os, sys
import email, smtplib
storage_folder = "data/export"
mail_server = 'server-address'
mail_username = 'mail-user'
mail_password = 'mail-password'
mail_to = 'mail-address-to'
mail_from = 'mail-sender'
def load_mails(file_folder):
#: scans desired folder for *.eml files
email_body = []
for dirname, dirnames, filenames in os.walk(file_folder):
for filename in filenames:
if filename.endswith('eml'):
f = open(os.path.join(dirname, filename))
email_body.append(f.read())
return email_body
def split_list(l, size):
#: split the mail-array to smaller chunks
return [l[i:i + size] for i in range(0, len(l), size)]
def send_mails(email_body):
smtp = smtplib.SMTP(mail_server, 587)
smtp.starttls()
smtp.login(mail_username, mail_password)
for idx, item in enumerate(email_body):
m = email.message_from_string(item)
m.replace_header("From", mail_from)
m.replace_header("To", mail_to)
m.replace_header("Subject", m['subject'])
print "Forwarding mail %d/%d: '%s' from '%s' to %s " % (
idx + 1, len(email_body), m['subject'], m['date'], mail_to)
smtp.quit()
if __name__ == '__main__':
if len(sys.argv) > 1:
chunk_size = int(sys.argv[1])
folder = sys.argv[2]
chunks = split_list(load_mails(folder), chunk_size)
pool = Pool(len(chunks))
pool.map(send_mails, chunks)
#! /usr/bin/env python
import os, sys
import email, smtplib
storage_folder = "data/export"
storage_header = 0
mail_server = 'server-address'
mail_username = 'mail-user'
mail_password = 'mail-password'
mail_to = 'mail-address-to'
mail_from = 'mail-sender'
def load_local_mails(file_folder):
#: scan desired folder for *.eml files
email_body = []
for dirname, dirnames, filenames in os.walk(file_folder):
for filename in filenames:
if filename.endswith('eml'):
f = open(os.path.join(dirname, filename))
email_body.append(f.read())
return email_body
def send_mail(email_body):
#: send mails
smtp = smtplib.SMTP(mail_server, 587)
smtp.starttls()
smtp.login(mail_username, mail_password)
for idx, item in enumerate(email_body):
m = email.message_from_string(item)
m.replace_header("From", mail_from)
m.replace_header("To", mail_to)
m.replace_header("Subject", m['subject'])
smtp.sendmail(mail_from, mail_to, m.as_string())
print "Forwarding mail %d/%d: '%s' from '%s' to %s " % (idx+1, len(email_body), m['subject'], m['date'], mail_to)
smtp.quit()
def main():
if len(sys.argv) > 1:
if sys.argv[1] == '--start':
send_mail(load_local_mails(sys.argv[2]))
else:
exit("Don't know what to do? :(. Goodbye")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment