電子メールメッセージにPDFファイルを添付しようとしています。Python電子メールPDF:一部のPDFが破損する
1つのPDF(Word文書をPDFに印刷)の場合、受信者は問題なくOutlookで開きます。 (数KB大きいことを除いて同じように見える)他のPDFファイルのためしかし
、彼らが破損して取得します。
Hereが失敗(壊れた)を使用するサンプルです。
import smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.utils import formatdate
from email import encoders
attachment_path=r'C:\Directory'+'\\'
login='login'
password='password'
part=MIMEBase('application',"octet-stream")
def message(attachment): #attachment is just the PDF file name
fromaddr = "[email protected]"
cc=fromaddr
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = "[email protected]"
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = "Subject"
body='''
<!DOCTYPE html>
<html>
<body>
<p><font face="Tahoma" size=2> I hope everything is going well.</p></font>
</body>
</html>
'''
msg.attach(MIMEText(body, 'html'))
part.set_payload(open(attachment_path+attachment,'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(attachment_path+attachment)))
msg.attach(part)
mail=smtplib.SMTP('Server',587)
mail.ehlo()
mail.starttls()
mail.login(login,password)
mail.sendmail(fromaddr,[toaddr,cc],msg.as_string())
私は次の代わりに、ベース64エンコーディングを使用しますが、無駄にしようとしている:事前に
encoders.encode_noop(part)
encoders.encode_7or8bit(part)
encoders.encode_quopri(part)
感謝を!私はコードの行の下に使用していると、それは私のために正常に動作している
part.set_payload(open(attachment_path+attachment,'rb').read())