Created
January 30, 2021 12:00
-
-
Save darideveloper/0d8feb89dcf0174f1d642fd5b8826c73 to your computer and use it in GitHub Desktop.
Adjuntar archivos a correos
This file contains hidden or 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
#! python3 | |
""" | |
Code for my youtube course: Python emails. | |
Youtube chanel (in spanish): https://www.youtube.com/channel/UCXWTlKzN_udf9LGqlDsuByg | |
""" | |
import smtplib, os | |
from email.mime.application import MIMEApplication | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
from email.utils import formatdate | |
# List of recipents | |
to_emails = { | |
"[email protected]": "Juan", | |
"[email protected]": "Maria", | |
"[email protected]": "Alberto" | |
} | |
file_list = [ | |
"file.pdf", | |
"img.jpg" | |
] | |
# Contect to smtp server and port | |
smtpObj = smtplib.SMTP ('smtp.gmail.com', 587) | |
# Send hello to smtp | |
smtpObj.ehlo() | |
# Active encriptation | |
smtpObj.starttls() | |
# Login | |
smtpObj.login ("[email protected]", "your_password") | |
# Loop for each email in list | |
for email, name in to_emails.items(): | |
# Make an instance of mime multipart to create the message | |
message = MIMEMultipart() | |
# Add main part to the email | |
message['From'] = "[email protected]" | |
message["To"] = email | |
message["Date"] = formatdate(localtime=True) | |
message["Subject"] = "Email with file" | |
# Add tex5t to the email | |
text = 'Good morning {} This is an example email'.format(name) | |
message.attach (MIMEText(text)) | |
# Loop for files in list | |
for file in file_list: | |
# Read file and create email part | |
file_binary = open(file, "rb") | |
part = MIMEApplication(file_binary.read(), name=os.path.basename(file)) | |
file_binary.close() | |
# Add file to the message | |
part['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path.basename(file)) | |
message.attach(part) | |
# Send email | |
smtpObj.sendmail('[email protected]', | |
email, | |
message.as_string()) | |
# Confirmation message | |
print ("Correo enviado a {}".format (name)) | |
# Close connection | |
smtpObj.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment