如何使用Python3将某些文件附加到MIME多部分电子邮件中? 我想将一些附件作为“可下载的内容”发送到我的HTML邮件(带有纯文本后备)。到目前为止找不到任何东西...
编辑:经过几次尝试,我才使它发送文件。感谢您的提示@tripleee。但是不幸的是,我的HTML现在以纯文本格式发送了。
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.utils import formatdate
from os.path import basename
import smtplib
login = "*********"
password = "*********"
server = "smail.*********:25"
files = ['Anhang/file.png']
# Create the root message and fill in the from, to, and subject headers
msg = MIMEMultipart('related')
msg['From'] = "*********"
msg['To'] = "*********"
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = "*********"
msg['Reply-To'] = "*********"
msg.preamble = 'This is a multi-part message in MIME format.'
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
with open('*********.txt', 'r') as plainTXT:
plain = plainTXT.read()
plainTXT.close()
msgAlternative.attach(MIMEText(plain))
with open('*********.html', 'r') as plainHTML:
html = plainHTML.read()
plainHTML.close()
msgAlternative.attach(MIMEText(html))
msg.attach(msgAlternative)
# Image
for f in files or []:
with open(f, "rb") as fp:
part = MIMEImage(
fp.read(),
Name=basename(f)
)
# closing file
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)
# create server
server = smtplib.SMTP(server)
server.starttls()
# Login Credentials for sending the mail
server.login(login, password)
# send the message via the server.
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
print("successfully sent email to %s:" % (msg['To']));
答案 0 :(得分:0)