当调用以下SMTP功能时,邮件将发送到我的邮箱,但日志文件附加为.bin文件类型。打开时,.bin文件会读取。如果它是.txt文件类型,但是我无法在我的移动设备上打开.bin文件,这对我来说是个大问题。有没有办法使用其原始文件类型将此文件附加到邮件?任何反馈都非常感谢。
编辑:当我从Windows机器运行文件时,文件以其原始文件类型(.txt)发送,但是当我在Linux机器上运行文件类型时,文件类型处理不当。我已经使用Outlook(首选)和Gmail对此进行了测试。 Outlook将文件识别为.bin文件类型,而Gmail根本无法识别文件类型。
from pathlib import Path
data_folder = Path("path/to/working/directory")
log_file = Path(data_folder / "log.txt")
def sendmail():
maildate = str(datetime.now().strftime("%m" + "/" + "%d" + "/" + "%Y"))
subjectdate = str("Subject - " + maildate)
import smtplib
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
msg = MIMEMultipart()
msg['Subject'] = subjectdate
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
attachment = MIMEBase('application', "octet-stream")
attachment.set_payload(open(log_file, "r").read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment, filename=log_file')
msg.attach(attachment)
s = smtplib.SMTP('[email protected]')
s.send_message(msg)
s.quit()
文件发送时没有扩展名,因为文件名被解释为“log_file”而不是log_file的值。下面的代码按预期工作,并正确地将文件附加到邮件。
from pathlib import Path
data_folder = Path("path/to/working/directory")
log_file = Path(data_folder / "log.txt")
def sendmail():
maildate = str(datetime.now().strftime("%m" + "/" + "%d" + "/" + "%Y"))
subjectdate = str("Subject - " + maildate)
import smtplib
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
msg = MIMEMultipart()
msg['Subject'] = subjectdate
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
attachment = MIMEBase('application', "octet-stream")
attachment.set_payload(open(log_file, "r").read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment, filename="log.txt"')
msg.attach(attachment)
s = smtplib.SMTP('[email protected]')
s.send_message(msg)
s.quit()