code snippet ですが、少々の修正で、動作すると思います
#!python # -*- coding: utf-8 -*- from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication import csv import io import smtplib import socket CONF={ "mail": {"smtp_server" : "xxx.xmile.sexy.co.jp", "port" : 587, "user_id" : "ないしょ", "user_pw" : "ないしょ", "from" : "ないしょ@example.com", "to" : ["ないしょ@example.com"], "cc" : [], }, } def main(): csv_for_espis = <省略> # 実fileに書き込まず、CSV添付する為、StringIO()を利用 dummy_csv_file = io.StringIO() csv_headers = [ "UserD","氏名","所属部所コード","日付","曜日", "入室時刻","退室時刻","最新入室時刻", "所属部所名","入室回数","退室回数" ] writer = csv.DictWriter(dummy_csv_file, fieldnames=csv_headers) writer.writeheader() writer.writerows(csv_for_espis) csv_data = dummy_csv_file.getvalue() io.StringIO().close() # windows用csvの為、文字コードは cp932 csv_data = csv_data.encode("cp932","ignore") # メール添付で送信 notify_by_email( csv_data ) logger.info("DONE "+func_name) def notify_by_email(start_end_csv_contents): message = MIMEMultipart() message["Subject"] = "連携CSVデータ" message["From"] = CONF["mail"]["from"] msg_body_tmpl = """e-SPIS の ご担当者様へ ※このメールは {hostname} {ip} にある RPA ({script}) から自動送信しています 連携用CSVを添付致しますので、ご確認をお願いします。 -- ないしょの署名 """ msg_body = msg_body_tmpl.format( hostname = socket.gethostname(), ip = socket.gethostbyname(socket.gethostname()), script = __file__ ) message.attach( MIMEText(msg_body,"plain", "utf-8") ) attachment = MIMEApplication(start_end_csv_contents) attachment.add_header("Content-Disposition", "attachment", filename="E_SPIS_WORK.CSV" ) message.attach( attachment ) tos = [] for mailto in CONF["mail"]["to"]: tos.append(mailto) if len(tos) == 0 : return to_addrs = tos message["To"] = ",".join(tos) message["Cc"] = ",".join( CONF["mail"]["cc"] ) to_addrs += CONF["mail"]["cc"] try: server = smtplib.SMTP(CONF["mail"]["smtp_server"], CONF["mail"]["port"]) #server.set_debuglevel(True) server.login( CONF["mail"]["user_id"], CONF["mail"]["user_pw"]) server.send_message( message, to_addrs=to_addrs ) except Exception as e: print(e) server.quit() if __name__ == '__main__': main()