-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
90 lines (69 loc) · 2.74 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import smtplib
import logging
import os
from configparser import ConfigParser
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from utils import get_contacts, get_template
def main():
config = ConfigParser()
config.read("config.cfg")
input_folder = config.get("config", "input_folder")
email_list = config.get("config", "email_list")
body_template = config.get("config", "body_template")
smtp_host = config.get("smtp", "host")
smtp_port = config.get("smtp", "port")
smtp_email = config.get("smtp", "email")
smtp_password = config.get("smtp", "password")
subject = config.get("smtp", "email_subject")
log_output = "log.txt"
logging.basicConfig(level=logging.INFO,
format="%(levelname)s - %(message)s",
handlers=[
logging.FileHandler(log_output, mode="w"),
logging.StreamHandler()
])
if not os.path.exists(input_folder) or not os.listdir(input_folder):
logging.error("Input folder doesn't exist or empty")
return
if not smtp_email or not smtp_password:
logging.error("Email or password empty")
return
try:
logging.info("Connecting to SMTP server ...")
smtp_server = smtplib.SMTP(host=smtp_host, port=smtp_port)
smtp_server.starttls()
smtp_server.login(smtp_email, smtp_password)
logging.info("Connected to SMTP server")
except Exception as e:
logging.error(f"Failed to connect to SMTP server: {e}")
return
names, emails, count = get_contacts(email_list)
email_body_template = get_template(body_template)
for line, (name, email) in enumerate(zip(names, emails)):
logging.info(
f"({line + 1}/{count}) Sending email to {name} ({email}) ... ")
try:
msg = MIMEMultipart()
message = email_body_template.substitute(NAME=name)
msg['From'] = smtp_email
msg['To'] = email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
with open(f"{input_folder}/{name}.png", 'rb') as fp:
img = MIMEImage(fp.read())
img.add_header(
'Content-Disposition',
'attachment',
filename=f"{name}.png")
msg.attach(img)
smtp_server.send_message(msg)
del msg
logging.info(f"Success sending email to {name} ({email})")
except Exception as e:
logging.error(f"Failed sending email: {e}")
smtp_server.quit()
logging.info("Done")
if __name__ == '__main__':
main()