我正在尝试将python 3.3中的smtp发送给文本文件中列出的收件人。
我收到的错误是:
session.sendmail(sender, recipient, msg.as_string())
smtplib.SMTPRecipientsRefused: {}
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 = 'Sender@gmail.com'
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()
答案 0 :(得分:1)
您想要仔细检查收件人代码。看起来你试图不止一次地使用文件的内容,这是行不通的 - 文件对象应理解为流,而不是数据块,所以一旦你完成{{1或者f.read()
一次,该流是空的,所以第二次这样做会产生一个空列表。您应该通过打印[i.strip() for i in mails.readlines()]
然后试试这个:
recipient
现在你应该有一个填充的收件人列表,然后到下一期!