python2.7 Gmail経由メール送信
Gmailサーバー経由でメール送信。
2段階認証を有効にしていない場合、安全性の低いアクセスを許可してもうまくいかなかった。
2段階認証を有効にしている場合、パスワードは2段階認証時のパスワード。
python2.7からau(ezweb.ne.jp)への送信確認済み。
# coding: utf-8 import email from email.header import decode_header from email.header import Header from email.MIMEText import MIMEText from email import Utils from smtplib import SMTP_SSL class GmailSMTPSender(object): def __init__(self, user, password): self.user = user self.password = password self.smtp_host = 'smtp.gmail.com' self.smtp_port = 465 self.email_default_encoding = 'iso-2022-jp' self.timeout = 60 def sendmail(self, fromAddr, toAddr, cc, bcc, subject, body): try: conn = SMTP_SSL(self.smtp_host, self.smtp_port) conn.login(self.user, self.password) msg = MIMEText(body, 'plain', self.email_default_encoding) msg['Subject'] = Header(subject, self.email_default_encoding) msg['From'] = fromAddr msg['To'] = ', '.join(toAddr) msg['Date'] = Utils.formatdate(localtime=True) conn.sendmail(fromAddr, toAddr, msg.as_string()) except: raise finally: conn.close() client = GmailSMTPSender('username', 'password') subject = u"件名" body = u"日本語でも大丈夫" client.sendmail('from_address', 'to_address', None, None, subject, body)