通过Python电子邮件库发送电子邮件会引发错误“预期字符串或类似字节的对象", [英] Sending an email via the Python email library throws error "expected string or bytes-like object"

查看:214
本文介绍了通过Python电子邮件库发送电子邮件会引发错误“预期字符串或类似字节的对象",的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to send a csv file as an attachment via a simple function in python 3.6.

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文件作为附件发送的指示?

Calling email() produces the error expected string or bytes-like object. Redefining server.sendmail("test@gmail.com", "testee@gmail.com", msg) as server.sendmail("atest@gmail.com", "testee@gmail.com", msg.as_string()) causes an email to be sent, but sends the csv file in the body of the email, NOT as an attachment. can anyone give me some pointers on how to send the csv file as an attachment?

推荐答案

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

1) You should use msg.as_string() if you call smtplib.SMTP.sendmail(). Alternatively, if you have Python 3.2 or newer, you can use server.send_message(msg).

2)您应该在邮件中添加一个正文.根据设计,没有人会看到序言.

2) You should add a body to your message. By design no one ever sees the preamble.

3)您应该使用content-disposition: attachment指示哪些部分是附件,哪些是内联.

3) You should use content-disposition: attachment to indicate which parts are attachments and which are inline.

尝试一下:

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

这篇关于通过Python电子邮件库发送电子邮件会引发错误“预期字符串或类似字节的对象",的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆