Python电子邮件发送类型错误:应为字符串或缓冲区

Python电子邮件发送类型错误:应为字符串或缓冲区,python,typeerror,smtplib,Python,Typeerror,Smtplib,好了,伙计们,我在互联网上搜索了很久,根本找不到答案。我尝试了很多建议,但似乎都没能奏效。我正在尝试使用python(smtplib和电子邮件模块)和gmail服务发送电子邮件。以下是我导入的软件包: import time, math, urllib2, urllib, os, shutil, zipfile, smtplib, sys from email.mime.text import MIMEText 以下是我发送电子邮件的def声明: def sendmessage(): prin

好了,伙计们,我在互联网上搜索了很久,根本找不到答案。我尝试了很多建议,但似乎都没能奏效。我正在尝试使用python(smtplib和电子邮件模块)和gmail服务发送电子邮件。以下是我导入的软件包:

import time, math, urllib2, urllib, os, shutil, zipfile, smtplib, sys
from email.mime.text import MIMEText
以下是我发送电子邮件的def声明:

def sendmessage():
print('== You are now sending an email to Hoxie. Please write your username below. ==')
mcusername = str(raw_input('>> Username: '))
print('>> Now your message.')
message = str(raw_input('>> Message: '))
print('>> Attempting connection to email host...')
fromaddr = 'x@gmail.com'
toaddrs = 'xx@gmail.com'
username = 'x@gmail.com'
password = '1013513403'
server = smtplib.SMTP('smtp.gmail.com:587')
subject = 'Email from',mcusername
content = message
msg = MIMEText(content)
msg['From'] = fromaddr
msg['To'] = toaddrs
msg['Subject'] = subject
try:
    server.ehlo()
    server.starttls()
    server.ehlo()
except:
    print('!! Could not connect to email host! Check internet connection! !!')
    os.system('pause')
    main()
else:
    print('>> Connected to email host! Attempting secure login via SMTP...')
    try:
        server.login(username,password)
    except:
        print('!! Could not secure connection! Stopping! !!')
        os.system('pause')
        main()
    else:
        print('>> Login succeeded! Attempting to send message...')
        try:
            server.sendmail(fromaddr, toaddrs, msg)
        except TypeError as e:
            print e
            print('Error!:', sys.exc_info()[0])
            print('!! Could not send message! Check internet connection! !!')
            os.system('pause')
            main()
        else:
            server.quit()
            print('>> Message successfully sent! I will respond as soon as possible!')
            os.system('pause')
            main()
我已经尽可能广泛地进行了调试,得到了以下结果:

>> Login succeeded! Attempting to send message...
TypeError: expected string or buffer
这意味着它成功登录,但在尝试发送消息时停止。 有一件事让我感到奇怪,那就是它没有指向哪里。而且我的代码可能不是很好,所以没有网络欺凌


任何帮助都将不胜感激!谢谢。

我猜罪魁祸首是这句话:

subject = 'Email from',mcusername
如果您希望将subject创建为字符串,那么它实际上会被制作成一个元组,因为您要传递两个值。您可能想做的是:

subject = 'Email from %s' % mcusername

另外,对于调试方面。。。包装所有异常并仅打印异常消息的方式就是丢弃有用的回溯(如果有)。在真正了解要处理的特定异常之前,您是否尝试过不包装所有内容?当您有语法错误时,这样做会使调试更加困难。

导致崩溃的原因是

server.sendmail(fromaddr, toaddrs, msg)
给它两个字符串和一个MIMEText实例;它希望消息以字符串的形式出现。[我认为它也希望地址以列表的形式出现,但它只需要一个字符串。]例如,您可以查看:

您必须将MIMEText转换为字符串,sendmail才会高兴。在修复了@jdi指出的主题bug(它生成了一条“AttributeError:'tuple'对象没有属性'lstrip'”消息)并将msg更改为
msg.as_string()
)后,您的代码对我有效

s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()