Last active
August 7, 2022 17:54
-
-
Save logston/088bf6e2435fe8ecac41ab18a93a012a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
""" | |
Back up at https://gist.github.com/logston/088bf6e2435fe8ecac41ab18a93a012a | |
""" | |
import base64 | |
import csv | |
import getpass | |
import smtplib | |
import time | |
import random | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
FROM_ADDRESS = base64.b64decode(b'cGF1bC5sb2dzdG9uQGNvbHVtYmlhLmVkdQo=').decode('utf-8') | |
SMTP_SERVER = 'in-v3.mailjet.com' | |
SMTP_PORT = 587 | |
def main(template_path, code_file, smtp_user, smtp_password): | |
print(f"Sending emails from {FROM_ADDRESS}") | |
with open(template_path) as fp: | |
template = fp.read() | |
with open(code_file) as fp: | |
reader = list(csv.DictReader(fp)) | |
# set up the SMTP server | |
s = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) | |
s.starttls() | |
s.login(smtp_user, smtp_password) | |
# For each contact, send the email: | |
for i, record in enumerate(reader): | |
# Don't send codes for empty lines or codes with no email | |
if not record['code'].strip() or not record['email']: | |
continue | |
print(f"{i} Sending to {record['email']}...") | |
msg = MIMEMultipart() # create a message | |
# setup the parameters of the message | |
msg['From'] = FROM_ADDRESS | |
msg['To'] = record['email'] | |
msg['Subject'] = f"Hi {record['email']}! Here's your server code..." | |
# add in the message body | |
msg.attach( | |
MIMEText( | |
template.format( | |
SERVER_CODE=record['code'], | |
EMAIL=record['email'], | |
), | |
'plain' | |
) | |
) | |
# send the message via the server set up earlier. | |
s.send_message(msg) | |
time.sleep(random.random() * 5) | |
# Terminate the SMTP session and close the connection | |
s.quit() | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument('template_path') | |
parser.add_argument('code_file') | |
args = parser.parse_args() | |
try: | |
print('Use Mailjet API key and Secret Key as user and password') | |
smtp_user = getpass.getpass('smtp user > ').strip() | |
if not smtp_user: | |
raise ValueError('Invalid SMTP user') | |
smtp_password = getpass.getpass('smtp password > ').strip() | |
if not smtp_password: | |
raise ValueError('Invalid SMTP password') | |
main(args.template_path, args.code_file, smtp_user, smtp_password) | |
except KeyboardInterrupt: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment