2017-04-18 99 views
0

我試圖用smpt來發送電子郵件與attachmant.However,但我的文件是「doc」或「txt」類型,我想發送附件中的「pdf」類型。是否有未知的參數可以做到這一點?python + smtp如何用附件發送電子郵件?

import smtplib 
import base64 
from email.mime.multipart import MIMEMultipart 
from email.mime.application import MIMEApplication 
import os 
server=smtplib.SMTP() 
server.connect("smtp..com") 
server.login("[email protected]","YYYYYY") 
msg=MIMEMultipart('') 
msg['From']="[email protected]" 
msg['Subject']="opp" 
with open("D:\log1.doc", 'rb') as f: 
    content = base64.standard_b64encode(f.read()).decode() 
part = MIMEApplication(content) 
newfilename = 'resume.pdf' 
part.add_header('Content-Disposition', 'attachment', filename=newfilename) 
msg.attach(part) 
msg['To']="[email protected]" 
server.send_message(msg) 

使用代碼,錯誤happended!附件文件無法打開!我怎麼解決這個問題? 感謝您的幫助。

+1

你混合了三件事情:SMTP是您正在使用的MIME類型發送*完成*電子郵件協議附件的內容類型,如電子郵件和聲明文件具有的實際內容類型。如果你想發送一個文檔文件爲pdf,你必須先轉換它。 –

回答

0
import string 
import time 
from email.header import Header 
from email.mime.text import MIMEText 
from getpass   import getpass 
from smtplib   import SMTP_SSL 
from email.MIMEMultipart import MIMEMultipart 

import smtplib 
msg = MIMEMultipart() 
filename = "textfile.txt" 
f = file(filename) 
fromaddr = '*******@gmail.com' 
toaddrs = 'gamil addr' 
#msg = 'There was a terrible error that occured and I wanted you to know!' 

attachment = MIMEText(f.read()) 
attachment.add_header('Content-Disposition', 'attachment', filename=filename)   
msg.attach(attachment) 
# Credentials (if needed) 
username = 'gamil addr' 
password = 'passwrd' 

# The actual mail send 
#server = smtplib.SMTP('smtp.gmail.com:587') 
server = smtplib.SMTP('smtp.gmail.com:587') 
server.starttls() 
server.login(username,password) 
server.sendmail(fromaddr, toaddrs, msg.as_string()) 
server.quit()