Вы можете достичь этого с помощью MIMEMultipart и MIMEText (вот документы: https://docs.python.org/3.4/library/email-examples.html)
В основном вы просто создаете вложение с помощью:
msg=MIMEMultipart()
part = MIMEBase('application', "octet-stream")
part.set_payload(open("attachment.txt", "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="attachment.txt"')
и прикрепляете его кэлектронная почта:
msg.attach(part)
Вот полный код:
import smtplib #import libraries for sending Emails(with attachment)
#this is to attach the attachment file
from email.mime.multipart import MIMEMultipart
#this is for attaching the body of the mail
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
server = smtplib.SMTP('smtp.gmail.com', 587) #connects to Email server
server.starttls()
server.user="your@email"
server.password="yourpassw"
server.login(server.user, server.password) #log in to server
#creates attachment
msg=MIMEMultipart()
part = MIMEBase('application', "octet-stream")
part.set_payload(open("attachment.txt", "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="attachment.txt"')
#attach the attachment
msg.attach(part)
#attach the body
msg.attach(MIMEText("your text"))
#sends mail with attachment
server.sendmail(server.user, ["user@1", "user@2", ...], msg=(msg.as_string()))
server.quit()