Вы можете отправлять электронные письма с помощью модуля Pythons smtplib
. Электронные письма в формате HTML поддерживаются в модуле email
.В прошлом я написал небольшой сценарий из учебника, который может вам помочь.Скрипт подключается к SMTP-порту Gmail и входит в учетную запись электронной почты, а затем отправляет электронное письмо.
import smtplib, ssl, email, random
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
# set the port and the server adres
smtp_server = "smtp.gmail.com"
port = 587
# Sender email details, this is from where the email is send
sender_email = "<YOUR_EMAIL>"
sender_email_password = "<PASSWORD>"
# This where the email goes to
receiver_email = "<EMAIL>"
# The name is taken from the first part of the email adres, before the '@'-sign
name = receiver_email.split("@")[0]
# Generate the message
message = MIMEMultipart("alternative")
message["Subject"] = str(random.randint(0,1000))
message["From"] = sender_email
message["To"] = receiver_email
# alternative text
text = "Hi there {}, How are you!".format(name)
# Fancy HTML email
html = "<h1>Hi there {}, How are you!!!!</h1>".format(name)
# Set a document as attachment, needs to be in the same directory
filename = "document.txt"
with open(filename, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(
"Content-Disposition",
f"attachment; filename= {filename}",
)
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
message.attach(part1)
message.attach(part2)
message.attach(part)
context = ssl.create_default_context()
# Send the email
try:
server = smtplib.SMTP(smtp_server, port)
server.ehlo()
server.starttls(context = context)
server.ehlo()
server.login(sender_email, sender_email_password)
server.sendmail(sender_email, receiver_email, str(message))
except Exception as e:
print(e)
finally:
server.quit()