2014-03-01 97 views
1

我想用python 3.3中的smtp發送一封電子郵件給在文本文件中列出的收件人。 我收到的錯誤是:
session.sendmail(sender, recipient, msg.as_string()) smtplib.SMTPRecipientsRefused: {}在python 3.3發送電子郵件給收件人.txt 3.3

哪裏是在sendmail的錯誤?謝謝!

全部下面的代碼:

#!/usr/bin/python 
import os, re 
import sys 
import smtplib 

from email.mime.image import MIMEImage 
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 

mails = open('/path/emails.txt','r+') 
mailList = mails.read() 
mailList = [i.strip() for i in mails.readlines()] 
directory = "/path/Desktop/" 

SMTP_SERVER = 'smtp.gmail.com' 
SMTP_PORT = 587 

sender = '[email protected]' 
password = "Sender'sPassword" 
recipient = [i.strip() for i in mails.readlines()] 
subject = 'Python (-++-) Test' 
message = 'Images attached.' 

def main(): 
    msg = MIMEMultipart() 
    msg['Subject'] = 'Python (-++-) Test' 
    msg['To'] = recipient 
    msg['From'] = sender 

    files = os.listdir(directory) 
    pngsearch = re.compile(".png", re.IGNORECASE) 
    files = filter(pngsearch.search, files) 
    for filename in files: 
     path = os.path.join(directory, filename) 
     if not os.path.isfile(path): 
      continue 

     img = MIMEImage(open(path, 'rb').read(), _subtype="png") 
     img.add_header('Content-Disposition', 'attachment', filename=filename) 
     msg.attach(img) 

    part = MIMEText('text', "plain") 
    part.set_payload(message) 
    msg.attach(part) 

    session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) 

    session.ehlo() 
    session.starttls() 
    session.ehlo 
    session.login(sender, password) 

    session.sendmail(sender, recipient, msg.as_string()) 
    session.quit() 

if __name__ == '__main__': 
    main() 

回答

1

你要仔細檢查收件人的代碼。看起來你試圖不止一次地使用文件的內容,這是行不通的 - 文件對象應該被理解爲流而不是數據塊,所以一旦你完成了f.read()[i.strip() for i in mails.readlines()]有一次,那個流是空的,所以第二次做這個就會產生一個空的列表。你應該通過打印recipient

檢查這個自己再試試這個:

mails = open('/path/emails.txt','r+') 
#mailList = mails.read() 
#mailList = [i.strip() for i in mails.readlines()] 
directory = "/path/Desktop/" 

SMTP_SERVER = 'smtp.gmail.com' 
SMTP_PORT = 587 

sender = '[email protected]' 
password = "Sender'sPassword" 
recipient = [i.strip() for i in mails.readlines()] 
print(recipient) 
subject = 'Python (-++-) Test' 
message = 'Images attached.' 

現在你應該有一個人口收件人列表,併到下一個問題!

相關問題