pymail/mail.py

87 lines
2.3 KiB
Python

import logging
import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from string import Template
import pandas as pd
from vars import *
def get_contacts(filename):
"""
Return the lists containing the infos
read from a file specified by filename.
"""
logging.debug(f'Loading contacts from {filename}...')
return pd.read_csv(filename)
def read_template(filename):
"""
Returns a Template object comprising the contents of the
file specified by filename.
"""
with open(filename, 'r', encoding='utf-8') as template_file:
template_file_content = template_file.read()
return Template(template_file_content)
def main():
logging.basicConfig(level=LOGLEVEL, format='%(asctime)s - %(levelname)s - %(message)s')
logging.info('Starting pymail')
contacts = get_contacts('contacts.csv')
message_template = read_template('message.html')
# set up the SMTP server
s = smtplib.SMTP(HOST, PORT)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)
logging.debug('Mail server is set up.')
logging.info(f'Starting to send mails to {len(contacts.index)} recipients, this might take a while...')
# For each contact, send the email:
for i in contacts.index:
logging.info(f"Sending email {i+1} of {len(contacts.index)}\n")
msg = MIMEMultipart() # create a message
# add in the actual person name to the message template
contact_dict = {col: contacts[col][i] for col in contacts.columns}
message = message_template.substitute(contact_dict)
# Prints out the message body for our sake
logging.debug(f"{message}\n")
# setup the parameters of the message
msg['From'] = MY_ADDRESS
msg['To'] = contacts[MAIL_COLUMN][i]
msg['Subject'] = SUBJECT
# add in the message body
msg.attach(MIMEText(message, 'html'))
if not DRY_RUN:
# send the message via the server set up earlier.
s.send_message(msg)
del msg
# Wait for DELAY_SEC seconds every WAIT_EVERY-th message
if (i + 1) % WAIT_EVERY == 0:
time.sleep(DELAY_SEC)
# Terminate the SMTP session and close the connection
s.quit()
logging.info('Done!')
if __name__ == '__main__':
main()