python 发送邮件不显示附件_python无法通过电子邮件发送附件文件
我建議使用
MIMEApplication代替附件.您也不需要手動執行所有有效負載編碼,因為這已經自動完成.這個例子對我有用:
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.utils import formataddr
from email.utils import make_msgid
from email.utils import formatdate
email = MIMEMultipart()
email['From'] = formataddr(('Jane Doe', 'jane@example.com'))
email['Subject'] = u'Test email'
email['Message-Id'] = make_msgid()
email['Date'] = formatdate(localtime=True)
email.attach(MIMEText(u'This is your email contents.'))
email.attach(MIMEApplication('your binary data'))
print email.as_string()
請注意,我還要注意在此處設置正確的Date和Message-Id標頭.
將其應用于您的代碼(并進行一些小的清理),我得到以下工作代碼:
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.utils import make_msgid
from email.utils import formatdate
def make_mail(address,body,format,mylist=[]):
msg = MIMEMultipart()
msg['To'] = address
msg['From'] = 'ggous1@gmail.com'
msg['Message-Id'] = make_msgid()
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(body, 'plain' if format == 'txt' else 'html'))
for filename in mylist:
part = MIMEApplication(open(filename).read())
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(filename))
msg.attach(part)
return msg
def send_mail(msg):
srv = smtplib.SMTP('smtp.gmail.com')
srv.set_debuglevel(1)
srv.ehlo()
srv.starttls()
srv.ehlo()
srv.login('username','pass')
srv.sendmail(msg['From'], msg['To'], msg.as_string())
srv.quit()
if __name__=="__main__":
address=raw_input('Enter an address to send email in the form "name@host.com" ')
body=raw_input('Enter the contents of the email')
format=raw_input('The format is txt or html?')
question=raw_input('Do you have any files to attach?Yes or No?')
mylist=[]
if question=='Yes' or question=='yes':
fn=raw_input('Enter filename')
mylist.append(fn)
msg = make_mail(address,body,format,mylist)
send_mail(msg)
總結
以上是生活随笔為你收集整理的python 发送邮件不显示附件_python无法通过电子邮件发送附件文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 冷却水的循环方式有哪几种_一种清洁环保高
- 下一篇: vue 分模块打包 脚手架_手动撸一个w