更改附件标题MIME python

问题描述 投票:0回答:1

我已尝试将所附PDF的标题从默认的“ noname”更改为其他标题。不幸的是,我代码的以下“ add_header”部分并未更改实际的标题名称。在不破坏或更改附件文件内容的情况下,还有其他选择吗?

fromaddr = '[email protected]'  
toaddrs  = '[email protected]'

username = 'XXXX'  
password = 'XXXXX'
msg = MIMEMultipart()
msg['Subject']='Spam'

msg.preamble = 'SDFSFSDF'


file=open(r'XXXXXX.pdf','rb').read()

msg.attach(MIMEApplication(file,'pdf'))

msg.add_header('XXXXXX', 'file', filename = 'XXXXXX.pdf')

server = smtplib.SMTP('smtp.gmail.com', 587)  
server.ehlo()
server.starttls()
server.login(username, password)  
server.sendmail(fromaddr, toaddrs, msg.as_string())  
time.sleep(2)

编辑

这是附件的文件标题:

enter image description here

python python-3.x email mime
1个回答
0
投票

您想要这样的东西:

msg.add_header("Content-Disposition", 'attachment; filename="%s"' % 'XXXXX.pdf')

将在邮件中产生此标头

'Content-Disposition: attachment; filename="XXXXX.pdf"'

用[替换原始add_header呼叫

msg.add_header("Content-Disposition", 'attachment; filename="%s"' % 'hello.pdf')

在smtp调试服务器中生成此输出*

b'Content-Type: multipart/mixed; boundary="===============3303386632460914267=="'                                                   
b'MIME-Version: 1.0'                                                                                                                
b'Subject: Spam'                                                                                                                    
b'Content-Disposition: attachment; filename="hello.pdf"'                                                                            
b'X-Peer: ::1'                                                                                                                      
b''                                                                                                                                 
b'SDFSFSDF'                                                                                                                         
b'--===============3303386632460914267=='                                                                                           
b'Content-Type: application/pdf'                                                                                                    
b'MIME-Version: 1.0'                                                                                                                
b'Content-Transfer-Encoding: base64'                                                                                                
b''
b'LotsOfBase64'                        

* python -m smtpd -n -c DebuggingServer localhost:1025

© www.soinside.com 2019 - 2024. All rights reserved.