Created
July 12, 2024 14:48
-
-
Save edib/0be9529ae2260df52e5c1a16d044bcb3 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
smtp_server = "" | |
port = 587 # For starttls | |
sender_email = "" | |
receiver_email = "" | |
password = "" | |
subject = "An email with attachment from Python" | |
body = """\ | |
Subject: Hi there | |
This message is sent from Python.""" | |
# Create a multipart message and set headers | |
message = MIMEMultipart() | |
message["From"] = sender_email | |
message["To"] = receiver_email | |
message["Subject"] = subject | |
message["Bcc"] = sender_email # Recommended for mass emails | |
# Add body to email | |
message.attach(MIMEText(body, "plain")) | |
filename = "pdf-test.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() | |
context = ssl.create_default_context() | |
context.check_hostname = False | |
context.verify_mode = ssl.CERT_NONE | |
with smtplib.SMTP(smtp_server, port) as server: | |
server.ehlo() # Can be omitted | |
server.starttls(context=context) | |
server.ehlo() # Can be omitted | |
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