schatzi-send-mail-to-members/send_all.py

107 lines
3.1 KiB
Python

# -*- coding: utf-8 -*-
"""
Created on Thu Jan 9 00:09:12 2020
@author: sky
"""
import smtplib
from string import Template
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import email.mime.application
MY_ADDRESS = 'venti@binary-kitchen.de'
PASSWORD = 'FILL ME'
pdf_dir = 'pdfs/'
host_ = 'mail.binary-kitchen.de'
port_ = 587
dry_run = True # do not send mail, but set everything up
def get_contacts(filename):
"""
Return two lists names, emails containing names and email addresses
read from a file specified by filename.
"""
names = []
pdfs = []
emails = []
with open(filename, mode='r', encoding='utf-8') as contacts_file:
for a_contact in contacts_file:
names.append(a_contact.split(";")[0])
pdfs.append(a_contact.split(";")[1])
emails.append((a_contact.split(";")[2].strip()))
return names, pdfs, emails
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():
names, pdfs, emails = get_contacts('addresslist.txt') # read contacts
message_template = read_template('message.txt')
# set up the SMTP server
s = smtplib.SMTP(host=host_, port=port_)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)
# For each contact, send the email:
for name, pdf, email_ in zip(names, pdfs, emails):
msg = MIMEMultipart() # create a message
# add in the actual person name to the message template
message = message_template.substitute(PERSON_NAME=name.title())
# Prints out the message body for our sake
# print(message)
# setup the parameters of the message
msg['From']=MY_ADDRESS
msg['To']=email_
msg['Subject']="Mitgliedsbeitrags- und Spendenquittung Binary Kitchen 2019"
# add in the message body
msg.attach(MIMEText(message, 'plain'))
# PDF attachment
filename=pdf_dir + pdf
try:
fp=open(filename,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(att)
# send the message via the server set up earlier.
if dry_run == False:
try:
s.send_message(msg)
except:
print("Could not send to",name, pdf, email_)
else:
print("Simulating...sending",name, pdf, email_)
except FileNotFoundError:
print(filename, 'File does not exist. Mail was not send')
del msg
# Terminate the SMTP session and close the connection
s.quit()
if __name__ == '__main__':
main()