0

参考:如何使用 Python 发送带有 .csv 附件的电子邮件

我正在尝试将 csv 文件附加到电子邮件中,但我收到了带有另一个 .msg 文件附件的电子邮件,并且 csv 附加在此 .msg 文件中。我按照上面参考中的示例进行操作。我是否缺少任何其他步骤?

import smtplib
import mimetypes
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from datetime import datetime
from glob import glob

import sys

# get csv files from folder
report_folder = 'sample'
csv_list = glob('.\\' + report_folder + '\\*.csv')

# get today's date
today_date = datetime.now().strftime('%Y-%m-%d')

# for testing
#today_date = '2021-06-03'

        
# prepare and send email
server_info = 'mail.abc.com'
emailfrom = 'NoReply'
sender_name = 'Some server'
emailtoName = 'Tom'
emailto = 'Tom@abc.com'
subject = 'csv-' + today_date
server_port = 25

fileToSend = 'abc.csv'


msg = MIMEMultipart()
msg["From"] = sender_name + ' <' + emailfrom + '>'
msg["To"] =  emailtoName + ' <' + emailto + '>'
msg["Subject"] = subject
msg.preamble = subject

ctype, encoding = mimetypes.guess_type(fileToSend)
if ctype is None or encoding is not None:
    ctype = "application/octet-stream"

maintype, subtype = ctype.split("/", 1)
if maintype == "text":
    fp = open(fileToSend)
    # Note: we should handle calculating the charset
    attachment = MIMEText(fp.read(), _subtype=subtype)
    fp.close()
else:
    fp = open(fileToSend, "rb")
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
msg.attach(attachment)    

server = smtplib.SMTP(server_info,server_port)
server.starttls()
server.sendmail(emailfrom, emailto, msg.as_string())
server.close()
4

0 回答 0