Python邮件发送器,出现了在2.7正常工作时未遇到的错误(已更新为3.x语法)

0 投票
1 回答
542 浏览
提问于 2025-04-18 00:56

我写了一个用Python发送邮件的程序,它可以登录到Gmail和Yahoo邮箱。我刚刚下载了Python 3.4(之前用的是Python 2.7)。我现在搞不清楚我的错误是什么,错误信息是:

"Traceback (most recent call last):
  File "C:/Users/Parker McKillop/Desktop/Email bomber.py", line 35, in <module>
    for i in range(1, total+1):
TypeError: Can't convert 'int' object to str implicitly"       

这是我的代码:

import os
import smtplib
import getpass
import sys

server = input ('Server Mail: ')
user = input('Username: ')
passwd = getpass.getpass('Password: ')


to = input('\nTo: ')
subject = input('Subject:')
body = input('Message:')
total = input('Number of send: ')

if server == 'gmail':
    smtp_server = 'smtp.gmail.com'
    port = 587
elif server == 'yahoo':
    smtp_server = 'smtp.mail.yahoo.com'
    port = 25
else:
    print('Applies only to gmail and yahoo')
    sys.exit()

print ('')

try:
    server = smtplib.SMTP(smtp_server,port)
    server.ehlo()
    if smtp_server == "smtp.gmail.com":
            server.starttls()
    server.login(user,passwd)
    for i in range(1, total+1):
        subject = os.urandom(9)
        msg = 'From: ' + user + '\nSubject: ' + subject + '\n' + body
        server.sendmail(user,to,msg)
        print ("\rTotal emails sent: %i" % i)
        sys.stdout.flush()
    server.quit()
    print ('\n Done !!!')
except KeyboardInterrupt:
    print ('[-] Canceled')
    sys.exit()
except smtplib.SMTPAuthenticationError:
    print ('\n[!] The username or password you entered is incorrect.')
    sys.exit()

谢谢大家的帮助!

1 个回答

1

在Python 3中,input这个函数总是返回一个字符串。所以,当你用input获取的值赋给total时,total实际上是一个字符串。这样,当Python尝试执行range(1, total+1)时,就会出错,因为range函数需要的是数字,而不是字符串。你需要把total的定义改成:

total = int(input('Number of send: '))

撰写回答