Edited at

Python3で日本語のメールを送信

More than 3 years have passed since last update.

Python3で日本語のメールを送信します。

#!/bin/env python3


import smtplib
from email.mime.text import MIMEText
import datetime

jp='iso-2022-jp'

# file.txt中に送信したい内容が入っている
fp = open('file.txt')
raw_msg = fp.read()
msg = MIMEText(raw_msg.encode(jp), 'plain', jp,)
fp.close()

fromaddr = "aaa@example.com"
toaddr = "bbb@example.com"

# Subject指定の時に使う
d = datetime.datetime.today()
date = d.strftime("%Y-%m-%d")

msg['Subject'] = date+" の使用情報"
msg['From'] = fromaddr
msg['To'] = toaddr

try:
server = smtplib.SMTP('localhost')
server.send_message(msg)
print("Successfully sent email")
except Exception:
print("Error: unable to send email")

## 参照
## http://w.builwing.info/2013/09/21/python3-3%E3%81%A7%E3%83%A1%E3%83%BC%E3%83%AB%E9%80%81%E4%BF%A1/