-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathautomate_email.py
More file actions
executable file
·72 lines (54 loc) · 2 KB
/
automate_email.py
File metadata and controls
executable file
·72 lines (54 loc) · 2 KB
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
import smtplib
from string import Template
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import credentials
def get_contacts(filename):
"""
Function to get all the name and email IDs of contacts in separate lists
:param filename: File containing contact list
:return: lists containing names and emails
"""
names = []
emails = []
with open(filename, encoding='utf-8') as contacts_file:
for contact in contacts_file:
names.append(contact.split()[0])
emails.append(contact.split()[1])
return names, emails
def read_template(filename):
"""
Returns a template comprising the contents of a file
:param filename: File containing the email message
:return: Template object
"""
with open(filename, encoding='utf-8') as template_file:
template = template_file.read()
return Template(template)
def main():
# get names and contact list
names, emails = get_contacts('my_contacts.txt')
message_template = read_template('message.txt')
# setup the SMTP server
server = smtplib.SMTP(credentials.HOST_NAME, credentials.PORT)
server.ehlo()
server.starttls()
server.login(credentials.ADDRESS, credentials.PASSWORD)
for name, email in zip(names, emails):
msg = MIMEMultipart() # create a message
# add the person name to the title
message = message_template.substitute(PERSON_NAME=name.title())
# setup the message parameters
msg['From'] = credentials.ADDRESS
msg['To'] = email
msg['Subject'] = 'Automated Email Sending with Python'
# add the message body
msg.attach(MIMEText(message, 'plain'))
# send the message via the server setup earlier
server.send_message(msg)
# server.sendmail(credentials.ADDRESS, 'thegeek.004@gmail.com', 'Hello')
del msg
# terminate the SMTP session and close the connection
server.quit()
if __name__ == '__main__':
main()