from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
from email.utils import formatdate
import smtplib
import ssl
if __name__ == '__main__':
# Gmailアカウント情報(★要設定★)
mail_username = '作成したGmailアカウント名'
mail_password = '作成したGmailアカウントのパスワード'
# メール情報(★必要に応じて変更★)
body = 'ここは本文です。'
subject = 'ここはタイトルです。'
to_addrs = ['example@gmail.com', 'example2@gmail.com'] # 送信したアドレスリスト
attach_files = ['aaa.zip'] # 添付したいローカルファイル名を設定
_msg = MIMEMultipart()
_msg['From'] = mail_username
_msg['To'] = "; ".join(to_addrs)
_msg['Subject'] = subject
_msg['Date'] = formatdate(timeval=None, localtime=True)
# 本文の追加
_msg.attach(MIMEText(body, "plain"))
# 添付ファイルの追加
for filename in attach_files:
with open(filename, 'rb') as _f:
part = MIMEBase('application', 'octet-stream')
part.set_payload(_f.read())
# base64 encode
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename= {}'.format(filename))
_msg.attach(part)
# セキュアなSSL接続で送信
context = ssl.create_default_context()
_smtp = smtplib.SMTP_SSL(host='smtp.gmail.com', port=465, timeout=10, context=context)
_smtp.login(user=mail_username, password=mail_password)
_smtp.sendmail(mail_username, to_addrs, _msg.as_string())
_smtp.close()