我正在尝试编写一个通过电子邮件发送附件的函数。
我有这段代码可以发送电子邮件,但没有附件。有谁知道我可以修改我的代码来做到这一点?
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
msg = MIMEText(open("/tmp/file.txt", "rb"))
msg["From"] = "me@example.com"
msg["To"] = "you@example.com"
msg["Subject"] = "This is the subject.
p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
p.communicate(msg.as_string())
答案 0 :(得分:0)
使用MIMEMultipart
作为消息
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
msg['From'] = "me@example.com"
msg['To'] = "you@example.com"
msg['Subject'] = "This is the subject."
用于附加文字
from email.mime.text import MIMEText
msg.attach(MIMEText("""Content"""))
#or
with open('text_file.txt', 'r') as text:
msg.attach(MIMEText(text.read()))
与其他附件类似(例如图片)
from email.mime.image import MIMEImage
with open('image_file.png', 'rb') as img:
msg.attach(MIMEImage(img.read()))
几个示例here
以及所有MIME objects
的列表