2014-01-23 81 views
0

我對編程很陌生,所以我來這裏尋求幫助。我正在嘗試製作一個簡單的郵件羣發器,目前不會使用它,但在將來的某個時候,我可能會在我的IT工作中使用它。我的代碼似乎不想爲我工作。用python編寫電子郵件

import sys 
import smtplib 
emailfile = raw_input('Please enter the name of the text file that includes all email addresses: ') 
emailtosendfrom = raw_input('Enter your email address to send from: ') 
msgfile = raw_input('Please enter the text file name that includes the message you want to send out :') 
email = open(emailfile, 'r') 
toaddrs = email 
msg = open(msgfile, 'r') 


# Credentials 
password = raw_input('Please enter your email password : ') 

# Send mail 
server = smtplib.SMTP('smtp.gmail.com:587') 
server.ehlo() 
server.starttls() 
server.login(emailtosendfrom,password) 
with open(emailfile) as f: 
    emailsort = f.readlines() 
    for user in emailsort: 
     server.sendmail(emailtosendfrom, user, msg) 
f.close() 
server.quit() 

此代碼返回錯誤:

Traceback (most recent call last): 
    File "mail.py", line 26, in <module> 
    server.sendmail(emailtosendfrom, line, msg) 
    File "C:\Python27\lib\smtplib.py", line 717, 
    esmtp_opts.append("size=%d" % len(msg)) 
TypeError: object of type 'file' has no len() 

任何幫助,將不勝感激。謝謝!

回答

0

消息應該是一個字符串,而不是文件。首先通過更換得到的消息體:

msg = open(emailfile, 'r') 

有:

with open(emailfile) as msg: 
    msgbody = msg.read() 

,然後修復循環本身:

server.sendmail(emailtosendfrom, user, msgbody) 

雖然沒有直接關係的問題,這裏是我的2cents:

  1. 使用模塊getpass詢問用戶密碼,以便它不會顯示在屏幕上。
  2. 你正在打開文件,但從不關閉它們。在這種情況下,這不是一個很大的問題,因爲腳本會在幾毫秒後終止。一般來說,你應該把所有東西都包裝在with區塊中。除了關閉文件句柄之外,他們還會明確文件的實際使用位置。
  3. 某些行是多餘的,如email = open(emailfile, 'r')toaddrs = email

最後,可以更換:

emailsort = f.readlines() 
for user in emailsort: 

有:

for user in f: 

但一定要剝去最後\n(或電子郵件地址將是錯誤的)。