在 Python 中发送带有 zip 文件的电子邮件
Sending email with zip file in Python
脚本正在运行,我收到了 zip 文件。但是,当我尝试打开 zip 文件(WinRaR 和 7-zip)时,出现错误 - 存档格式未知或已损坏。可能与编码有关???
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import smtplib
def send_mail():
sender = '*****@mail.ru'
password = '*************'
smtp_obj = smtplib.SMTP('smtp.mail.ru', 587)
smtp_obj.starttls()
msg = MIMEMultipart()
msg['Subject'] = 'Data from Experiment'
msg['From'] = sender
msg['To'] = sender
with open(r'C:\Users\Admin\Desktop\Python\Python + SQL\Send_email\arch\arch.zip',encoding='CP866') as file:
# Attach the file with filename to the email
msg.attach(MIMEApplication(file.read(), Name='arch.zip'))
# Login to the server
smtp_obj.login(sender, password)
# Convert the message to a string and send it
smtp_obj.sendmail(sender, sender, msg.as_string())
#smtp_obj.quit()
send_mail()
打开 zip 文件时不要传递编码。那是二进制数据,应该这样对待! open(..., 'b')
脚本正在运行,我收到了 zip 文件。但是,当我尝试打开 zip 文件(WinRaR 和 7-zip)时,出现错误 - 存档格式未知或已损坏。可能与编码有关???
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import smtplib
def send_mail():
sender = '*****@mail.ru'
password = '*************'
smtp_obj = smtplib.SMTP('smtp.mail.ru', 587)
smtp_obj.starttls()
msg = MIMEMultipart()
msg['Subject'] = 'Data from Experiment'
msg['From'] = sender
msg['To'] = sender
with open(r'C:\Users\Admin\Desktop\Python\Python + SQL\Send_email\arch\arch.zip',encoding='CP866') as file:
# Attach the file with filename to the email
msg.attach(MIMEApplication(file.read(), Name='arch.zip'))
# Login to the server
smtp_obj.login(sender, password)
# Convert the message to a string and send it
smtp_obj.sendmail(sender, sender, msg.as_string())
#smtp_obj.quit()
send_mail()
打开 zip 文件时不要传递编码。那是二进制数据,应该这样对待! open(..., 'b')