SikuliX:メール送信(添付ファイル付き)

シナリオ

  • smtpサーバ:認証なし
  • 送信元:hoge@example.com
  • 宛先 :foo@example.com
  • 添付ファイルのパス:c:\attach\添付.xlsx

サンプルコード

import smtplib
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.utils import formatdate
from email import encoders
from os.path import basename

# send_mail_message
# subject  : 件名
# from_adr : 送信元アドレス
# to_adr   : 宛先アドレス カンマ区切りで複数のアドレス指定可能 (例)hoge@example.com,foo@example.com
# body     : 本文
# attach   : 添付ファイルパス
def send_mail_message(subject, from_adr, to_adr, body, attach):
    encoding = "utf-8"
    msg = MIMEMultipart()
    msg["Subject"] = subject
    msg["From"] = from_adr
    msg["To"] = to_adr
    msg["Date"] = formatdate()
    msg.attach(MIMEText(body, "plain", encoding))

    #ファイル添付
    if not (attach == None or attach == ""):
        path = attach
        with open(path, "rb") as f:
            txt_file = MIMEApplication(f.read(), Name=basename(path))
        txt_file["Content-Disposition"] = "attachment; filename=" + basename(path).encode(encoding)
        msg.attach(txt_file)

    #メール送信
    smtp = smtplib.SMTP("メールサーバ", 25)
    smtp.sendmail(from_adr, to_adr.split(","), msg.as_string())
    smtp.close()    

# メールアドレス
from_mail = "hoge@example.com"
to_mail = "foo@example.com"
# メールの件名
mail_subject = u"メール送信テスト"
# 添付ファイルパス
attach_path = u"C:\\attach\\添付.xlsx"
# メールの本文
body  = u"テストメール"
# 添付ファイル指定
attach = attach_path if os.path.exists(attach_path) else None
# メール送信
send_mail_message(mail_subject, from_mail, to_mail, body, attach)