[英]Sending an email with attachment
我正在尝试编写一个发送带有附件的电子邮件的函数。 目前,它会发送一封电子邮件,但没有附件。 有人可以评论吗?
msg = MIMEMultipart()
msg['From'] = my email
msg['To'] = client email address
msg['Subject'] = subject
body = content
msg.attach(MIMEText(body, 'plain'))
##### Load the address of the file which should be attached*********************************
filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("Text
files","*.txt"),("all files","*.*")))
Myfile = open(filename)
attachment = MIMEText(Myfile.read())
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachment)
mail = smtplib.SMTP('smtp.gmail.com', 587)
msg = f'Subject: {subject}\n\n{content}'
mail.ehlo()
mail.starttls()
mail.login('My email address', 'password')
mail.sendmail('client email', My email address, msg)
mail.close()
谢谢大家
首先,正如我在评论中提到的,你在这里覆盖了msg
:
msg = f'Subject: {subject}\n\n{content}'
此时,用于指向的MIMEMultipart
对象msg
被销毁,您将只发送该新字符串。 难怪为什么没有附件:这个字符串显然没有附件。
现在,您应该真正使用email
模块的新 API,如文档中所示。 但既然你已经使用旧的API(在MIMEMultipart
类,例如),你需要转换msg
为一个字符串,如这里:
# This is copied straight from the last link
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
...
part1 = MIMEText(text, 'plain') # example attachment
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
mail.sendmail(
me, you,
msg.as_string() # CONVERT TO STRING
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.