-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsendmail.py
67 lines (53 loc) · 2.24 KB
/
sendmail.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
import functions
import smtplib
# from email.message import EmailMessage
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# subject = "An email with attachment from Python"
# body = "This is an email with attachment sent from Python"
# sender_email = "[email protected]"
# receiver_email = "[email protected]"
# password = input("Type your password and press enter:")
def send(password, addr_to="", subject="", message="", filename=None, addr_from=""):
if len(addr_to) > 0 and len(subject) > 0:
pass
else:
print(addr_to, subject, message, filename)
raise AttributeError("Receiver and subject must be given!")
SERVER, PORT, USER, PASSWORD = functions.parseCredentials(pwd=password)
# Create a multipart message and set headers
msg = MIMEMultipart()
msg["From"] = USER if not addr_from else addr_from
msg["To"] = addr_to
msg["Subject"] = subject
# Add body to email
msg.attach(MIMEText(message, "plain"))
if filename is not None:
# Open PDF file in binary mode
with open(filename, "rb") as attachment:
print("Opening attachment file ({file})…".format(file=filename))
# 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())
# Encode file in ASCII characters to send by email
encoders.encode_base64(part)
# Add header as key/value pair to attachment part
part.add_header(
"Content-Disposition",
f"attachment; filename= {filename}".format(filename=filename.split("/")[-1]),
)
print("Adding attachment file to the email…")
# Add attachment to message and convert message to string
msg.attach(part)
text = msg.as_string()
connection = smtplib.SMTP(host=SERVER, port=PORT)
connection.starttls()
print("Connecting to {}...".format(SERVER))
connection.login(USER, PASSWORD)
print("Sending message...")
connection.sendmail(USER, addr_to, text)
connection.quit()
functions.printInGreen("Success")