通过Python电子邮件库发送电子邮件将引发错误“预期的字符串或字节类对象”

2024-09-28 17:04:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过python3.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文件作为附件发送的建议吗?在


Tags: 文件csvfromtestimportcom附件server
1条回答
网友
1楼 · 发布于 2024-09-28 17:04:47

1)如果调用smtplib.SMTP.sendmail(),则应使用msg.as_string()。或者,如果您有python3.2或更新版本,您可以使用^{}。在

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()

相关问题 更多 >