我正在尝试使用python发送一封电子邮件,其中包含gzip格式的文件作为附件。
但是尝试发送文件时出现错误。这是我得到的例外:
Exception: 'charmap' codec can't decode byte 0x90 in position 75: character maps to <undefined>
这就是我在代码中所做的:
import gzip
destination = 'path/to/file'
to_addr = input("Enter the recipient's email address: ")
from_addr = 'cloudops@noreply.company.com'
subject = "Commpany AWS Billing Info "
content = "email to the user about the file"
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = subject
body = MIMEText(content, 'html')
msg.attach(body)
server = smtplib.SMTP('smtpout.us.companyworld.company.com', 25)
filename = destination
try:
with open(filename, 'r') as f:
part = MIMEApplication(f.read(), Name=basename(filename))
part['Content-Disposition'] = 'attachment; filename="{}"'.format(basename(filename))
msg.attach(part)
server.send_message(msg, from_addr=from_addr, to_addrs=[to_addr])
print("Email was sent to: %s" % to_addr)
except Exception as e:
print("Exception: ", e)
print("Email was not sent.")
我要发送的文件是在以下行的另一个函数中创建的:
import pandas
read_sql = 'select * from somedb'
mydb = mysql.connector.connect(user='x', password='x',host='x',database='aws_bill')
results = pandas.read_sql_query(read_sql, mydb)
results.to_csv(destination, index=False, encoding='utf8', compression='gzip')
如何解决此问题并发送附件?
答案 0 :(得分:1)
问题是这一行:
with open(filename, 'r') as f:
您正在以文本模式打开gzip压缩文件,因此Python尝试对其进行解码;压缩后的文件应以 binary 模式打开,如下所示:
with open(filename, 'rb') as f: