Python 发送带有附件的电子邮件
我正在尝试写一个函数,发送一封带有附件的电子邮件。目前,它发送了一封电子邮件,但没有附件。你能评论一下吗Python 发送带有附件的电子邮件,python,python-3.x,email,Python,Python 3.x,Email,我正在尝试写一个函数,发送一封带有附件的电子邮件。目前,它发送了一封电子邮件,但没有附件。你能评论一下吗 msg = MIMEMultipart() msg['From'] = my email msg['To'] = client email address msg['Subject'] = subject body = content msg.attach(MIMEText(body, 'plain')) ##### Load
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
被销毁,您将只发送该新字符串。难怪没有附件:这个字符串显然没有附件
现在,您应该真正使用电子邮件
模块的新API,如图所示。但由于您已经在使用传统API(例如,MIMEMultipart
类),因此需要将msg
转换为字符串,如下所示:
“你能有人评论吗?”-当然,我在这里,评论你的帖子!你面临的实际问题是什么?如上所述,“目前,它发送一封电子邮件,但没有附件。”你在这里覆盖了
msg
:msg=f'Subject:{Subject}\n\n{content}
,所以你只发送这个字符串,而不是在这里创建的对象:msg=MIMEMultipart()
,谢谢,我试着了解了“msg=f'Subject:{Subject}\n\n{content}”但开始抛出其他错误,如“return\u compile(pattern,flags).sub(repl,string,count)TypeError:expected string或bytes like object”多谢了,我设法解决了这个问题。现在一切正常。
# 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
)