我使用的是python3,我试图在电子邮件中附加一个文件。我对MIME和SMTP很陌生。 这就是我的功能:
def func():
path = mypath
for file in glob.glob(path + "\\happy*"):
print(file)
sender = myemail
senderto = someonesemail
msg = MIMEMultipart('alternative')
msg['Subject'] = 'The File'
msg['From'] = sender
msg['To'] = senderto
body = "File"
msg.attach(MIMEText(body, 'plain'))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(file, encoding='charmap').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % file)
msg.attach(part)
global smtpSettings
smtpSettings = smtplib.SMTP(host=myhost, port=587)
print("Step 1 Complete")
smtpSettings.login(smtpusername, smtppassword)
print("Step 2 Complete")
smtpSettings.sendmail(sender, senderto, msg.as_string)
print("Step 3 Complete")
smtpSettings.quit()
print("Success")
旁注:senderto=接收方。 我得到的输出是:
^{pr2}$
我是yagmail的维护者,这是一个包,它使发送电子邮件(带附件或不带附件)变得更加容易。在
发送电子邮件只需要三行。不错!在
内容将巧妙地猜测
file
变量字符串指向一个文件,并因此附加该文件。在完整代码可能是:
^{2}$在步骤3中修复,更改
到
^{2}$因为
as_string
是一种方法相关问题 更多 >
编程相关推荐