我对编程很新,所以我来这里寻求帮助。我试图制作一个简单的群发电子邮件以获得乐趣,目前不会使用此功能,但未来的某个时候我可能会参与我的IT工作。我的代码似乎不想为我工作。
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 :(得分:0)
消息应该是字符串,而不是文件。首先通过替换:
获取邮件正文msg = open(emailfile, 'r')
使用:
with open(emailfile) as msg:
msgbody = msg.read()
然后用:
修复循环本身server.sendmail(emailtosendfrom, user, msgbody)
虽然与问题没有直接关系,但这是我的2cents:
getpass
向用户询问密码,以便它不会显示在屏幕上。with
块中。除了关闭文件句柄外,它们还会清楚文件的实际使用位置。email = open(emailfile, 'r')
和toaddrs = email
。最后,您可以替换:
emailsort = f.readlines()
for user in emailsort:
使用:
for user in f:
但请务必删除最终\n
(或电子邮件地址错误)。