Skip to content

Instantly share code, notes, and snippets.

@darideveloper
Created January 30, 2021 12:02
Show Gist options
  • Save darideveloper/ef8230c2bd68f745f3ec1ac083701626 to your computer and use it in GitHub Desktop.
Save darideveloper/ef8230c2bd68f745f3ec1ac083701626 to your computer and use it in GitHub Desktop.
Enviar correos html
#! 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