2014-04-19 64 views
11

好的,我知道有幾個問題可以解決這個問題,但我找不到一種方法使它正常工作。我會認爲它和下面的代碼一樣簡單,但是這不會附加我的文件。任何幫助將不勝感激。我對Python也很陌生。是否有我應該導入的郵件模塊以使該功能有效?如何使用Python發送帶有.csv附件的電子郵件

import smtplib 
fromaddr = "[email protected] 
toaddrs = "[email protected] 

msg = "help I cannot send an attachment to save my life" 
attach = ("csvonDesktp.csv") 

username = user 
password = password 

server = smtplib.SMTP('smtp.gmail.com:587') 
server.starttls() 
server.login(username,password) 
server.sendmail(fromaddr, toaddrs, msg, attach) 
server.quit() 
+2

http://stackoverflow.com/questions/9541837/attach-a-txt-file-in-python- smtplib – Toote

回答

44

發送包含適當MIME類型的多部分電子郵件。

https://docs.python.org/2/library/email-examples.html

所以可能是這樣的(我測試了這一點):

import smtplib 
import mimetypes 
from email.mime.multipart import MIMEMultipart 
from email import encoders 
from email.message import Message 
from email.mime.audio import MIMEAudio 
from email.mime.base import MIMEBase 
from email.mime.image import MIMEImage 
from email.mime.text import MIMEText 

emailfrom = "[email protected]" 
emailto = "[email protected]" 
fileToSend = "hi.csv" 
username = "user" 
password = "password" 

msg = MIMEMultipart() 
msg["From"] = emailfrom 
msg["To"] = emailto 
msg["Subject"] = "help I cannot send an attachment to save my life" 
msg.preamble = "help I cannot send an attachment to save my life" 

ctype, encoding = mimetypes.guess_type(fileToSend) 
if ctype is None or encoding is not None: 
    ctype = "application/octet-stream" 

maintype, subtype = ctype.split("/", 1) 

if maintype == "text": 
    fp = open(fileToSend) 
    # Note: we should handle calculating the charset 
    attachment = MIMEText(fp.read(), _subtype=subtype) 
    fp.close() 
elif maintype == "image": 
    fp = open(fileToSend, "rb") 
    attachment = MIMEImage(fp.read(), _subtype=subtype) 
    fp.close() 
elif maintype == "audio": 
    fp = open(fileToSend, "rb") 
    attachment = MIMEAudio(fp.read(), _subtype=subtype) 
    fp.close() 
else: 
    fp = open(fileToSend, "rb") 
    attachment = MIMEBase(maintype, subtype) 
    attachment.set_payload(fp.read()) 
    fp.close() 
    encoders.encode_base64(attachment) 
attachment.add_header("Content-Disposition", "attachment", filename=fileToSend) 
msg.attach(attachment) 

server = smtplib.SMTP("smtp.gmail.com:587") 
server.starttls() 
server.login(username,password) 
server.sendmail(emailfrom, emailto, msg.as_string()) 
server.quit() 
+0

傑米,這太棒了!感謝您的幫助! – JDS

+0

優秀的樣品。我喜歡你是如何通用的,並使用庫來獲取mimetypes而不是對其進行硬編碼。 –

相關問題