Mee*_*eem 8 python csv email smtplib python-3.x
我正在尝试通过 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()
Run Code Online (Sandbox Code Playgroud)
调用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)msg.as_string()如果你打电话,你应该使用smtplib.SMTP.sendmail()。或者,如果您有 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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4472 次 |
| 最近记录: |