-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmailsender.py
86 lines (66 loc) · 2.48 KB
/
mailsender.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
from parser import parsefile
import smtplib
import ssl
from MailDeets import MailDeets
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
"""
MailDeets.py
class MailDeets:
def __init__(self):
self.mymail = 'your-gmail-id'
self.password = 'your-password'
self.teamsusername = 'teamsusername'
"""
# get the filepath to the data
filepath = './data/data.csv'
attachmentfile = input(
"Path of file to attach (leave empty for no attachment): ")
# instantiate an object of the MailDeets class. (not included in the repo)
mailinfo = MailDeets()
sender = mailinfo.mymail # the self.mymail attribute has the mail id of the sender
# the self.password attribute contains the password for accessing the smtp server
password = mailinfo.password
# receiver = sender # for testing purposes only
subject = 'add the subject here'
body = """
add the message body here
"""
message = MIMEMultipart()
message["From"] = sender
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
# parses the entire dataset into a list of email addresses (change as per schema of dataset)
receivers = parsefile(filepath)
PORT = 465 # assign smtp port
sslcontext = ssl.create_default_context()
connection = smtplib.SMTP_SSL("smtp.gmail.com", PORT, context=sslcontext)
connection.login(sender, password) # login to smtp server
try:
with open(attachmentfile, "rb") as attachment:
# Add file as application/octet-stream
# Email client can usually download this automatically as attachment
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(
"Content-Disposition",
f"attachment; filename= {attachmentfile}",)
message.attach(part)
except Exception as e:
if attachmentfile:
print("Error opening attached file. Check the file path and permissions")
ans = input("Continue without attaching file? (y/N)")
if ans in ["n", "N"]:
exit()
elif ans not in ["y", "Y"]:
print("Unexpected input, exiting")
exit(1)
message = message.as_string()
i = 1 # counter for number of mails sent. After 85 or so, the server logs you out for 2 mins, gotta log in and start again
for rec in receivers:
connection.sendmail(sender, rec, message)
print(str(i) + ": Message sent!!") # confirmation message
i = i+1