エクセル添付ファイル付きメール送信プログラム
添付ファイルとしてエクセルのファイルを添付したメールを送信するプログラムをpythonで書いた。
参考にさせていただいたのは以下のサイト。
http://labs.unoh.net/2007/06/python_2.html
http://semanticlog.blogspot.com/2008/02/python-smtp.html
http://jeap-res.ams.eng.osaka-u.ac.jp/~sumioka/wiki/wiki.cgi?page=Python+Memo
http://d.hatena.ne.jp/aqvi/20081115/1226742281
スクリプトは以下の通り。
# -*- coding: utf-8 -*- import os.path import datetime import smtplib from email import Encoders from email.MIMEText import MIMEText from email.Header import Header from email.Utils import formatdate from email.MIMEBase import MIMEBase from email.MIMEMultipart import MIMEMultipart def send(from_addr, to_addr, msg): s = smtplib.SMTP('mail.xxxx.co.jp') if type(to_addr) != list: to_addr = [to_addr] s.sendmail(from_addr, to_addr, msg.as_string()) s.close() def create_message3(from_addr, to_addr, subject, body, attach_file, encoding, filename): msg = MIMEMultipart() msg['Subject'] = Header(subject.encode(encoding), encoding) #ウノウラボさんの例のようにsubjectをエンコードしないと文字化けが起こってしまう。何か違いがあるのだろうか。 msg['From'] = from_addr if type(to_addr) == list: to_addr = ";".join([str(i) for i in to_addr]) msg['To'] = to_addr msg['Date'] = formatdate() body = MIMEText(body.encode(encoding), 'plain', encoding) msg.attach(body) #ここもやはりbodyをエンコードしなきゃ文字化けしてしまう。 attachment = MIMEBase('application', 'vnd.ms-excel') file = open(attach_file, 'rb') attachment.set_payload(file.read()) file.close() Encoders.encode_base64(attachment) msg.attach(attachment) attachment.add_header("Content-Disposition", "attachment; filename=%s" %filename.encode(encoding)) #ここでもfilenameをエンコードしないと文字化けしてしまう。 return msg if __name__== '__main__': #to_addr = "xxxx@xxxx.co.jp" from_addr = 'xxxx@xxxx.co.jp' to_addr = ['xxxx@xxxx.jp', 'xxxx@xxxx.co.jp'] PATH = r"x:\xxxx\xxxx" FILENAME = u"xxxx.xls" today = datetime.datetime.today() body = u"""本文 """ % (today.year, today.month, today.day,) msg = create_message3(from_addr, to_addr, u'xxxx', body, os.path.join(PATH, FILENAME), 'iso-2022-jp', u'xxxx.xls') send(from_addr, to_addr, msg)