通过 Python 电子邮件库发送电子邮件会引发错误 "expected string or bytes-like object"

Sending an email via the Python email library throws error "expected string or bytes-like object"

我正在尝试通过 python 3.6 中的一个简单函数将 csv 文件作为附件发送。

from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def email():


    msg = MIMEMultipart()
    msg['Subject'] = 'test'
    msg['From'] = 'test@gmail.com'
    msg['To'] = 'testee@gmail.com'
    msg.preamble = 'preamble'

    with open("test.csv") as fp:
        record = MIMEText(fp.read())
        msg.attach(record)

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login("test@gmail.com", "password")
    server.sendmail("test@gmail.com", "testee@gmail.com", msg)
    server.quit()

调用 email() 产生错误 expected string or bytes-like object。将 server.sendmail("test@gmail.com", "testee@gmail.com", msg) 重新定义为 server.sendmail("atest@gmail.com", "testee@gmail.com", msg.as_string()) 会导致发送电子邮件,但会在电子邮件正文中发送 csv 文件,而不是作为附件发送。谁能给我一些关于如何将 csv 文件作为附件发送的指示?

1) 如果调用smtplib.SMTP.sendmail(),则应使用msg.as_string()。或者,如果您有 Python 3.2 或更新版本,则可以使用 server.send_message(msg).

2) 您应该在邮件中添加正文。按照设计,没有人会看到序言。

3) 您应该使用 content-disposition: attachment 来指明哪些部分是附件,哪些部分是内联的。

试试这个:

def email():


    msg = MIMEMultipart()
    msg['Subject'] = 'test'
    msg['From'] = 'XXX'
    msg['To'] = 'XXX'
    msg.preamble = 'preamble'

    body = MIMEText("This is the body of the message")
    msg.attach(body)

    with open("test.csv") as fp:
        record = MIMEText(fp.read())
        record['Content-Disposition'] = 'attachment; filename="test.csv"'
        msg.attach(record)

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login("XXX", "XXX")
    server.sendmail("XXX", "XXX", msg.as_string())
    server.quit()