Last active
February 17, 2020 10:38
-
-
Save alexmacniven/f83ec81d70f077ff4db5c31f93de04e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://realpython.com/python-send-email/ | |
# https://stackoverflow.com/a/12424439 | |
import email, smtplib | |
from email import encoders | |
from email.mime.base import MIMEBase | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
subject = "" | |
body = "" | |
sender_email = "" | |
receiver_email = "" | |
smtp_server = "" | |
smtip_port = 465 | |
password = "" | |
# Create a multipart message and set headers | |
message = MIMEMultipart() | |
message["From"] = sender_email | |
message["To"] = receiver_email | |
message["Subject"] = subject | |
message["Bcc"] = receiver_email # Recommended for mass emails | |
# Add body to email | |
message.attach(MIMEText(body, "plain")) | |
filename = "document.pdf" # In same directory as script | |
# Open PDF file in binary mode | |
with open(filename, "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()) | |
# 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}", | |
) | |
# Add attachment to message and convert message to string | |
message.attach(part) | |
text = message.as_string() | |
with smtplib.SMTP(smtp_server, smtp_port) as server: | |
server.ehlo() | |
server.starttls() | |
server.login(sender_email, password) | |
server.sendmail(sender_email, receiver_email, text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment