このトピックでは、Python 2 での SMTP 呼び出しの例を示します。
SMTP プロトコルを介して Python を使用してメールを送信する
# -*- coding:utf-8 -*-
import smtplib
import email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email.header import Header
# 送信元アドレス。このアドレスはコンソールで作成されます。
username = '***'
# 送信元パスワード。このパスワードはコンソールで作成されます。
password = '***'
# カスタムの返信先アドレス。
replyto = '***'
# 受信者アドレスまたは受信者アドレスのリスト。複数の受信者がサポートされています。
# 許可される受信者の具体的な数については、プロダクトの仕様をご参照ください。
#receivers = ['address1@example.com', 'address2@example.com']
#rcptto = ','.join(rcptto)
rcptto = '***'
# 代替構造を構築します。
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('Custom email subject'.decode('utf-8')).encode()
msg['From'] = '%s <%s>' % (Header('Custom sender nickname'.decode('utf-8')).encode(), username)
msg['To'] = rcptto
msg['Reply-to'] = replyto
msg['Message-id'] = email.utils.make_msgid()
msg['Date'] = email.utils.formatdate()
# 代替構造の text/plain 部分を構築します。
textplain = MIMEText('Custom plain text content', _subtype='plain', _charset='UTF-8')
msg.attach(textplain)
# 代替構造の text/html 部分を構築します。
texthtml = MIMEText('Custom HTML content', _subtype='html', _charset='UTF-8')
msg.attach(texthtml)
# メールを送信します。
try:
client = smtplib.SMTP()
# Python 2.7 以降では、この方法でクライアントを作成して SSL を使用します。
#client = smtplib.SMTP_SSL()
# 標準の SMTP ポートは 25 または 80 です。
client.connect('smtpdm.aliyun.com', 25)
# DEBUG モードを有効にします。
client.set_debuglevel(0)
client.login(username, password)
# 送信元アドレスと認証アドレスは同じである必要があります。
# 注: DATA コマンドの戻り値を取得するには、
# SMTP.mail、SMTP.rcpt、および SMTP.data メソッドを直接使用します。
client.sendmail(username, rcptto, msg.as_string())
# 複数の受信者に送信するには:
#client.sendmail(username, receivers, msg.as_string())
client.quit()
print 'メールの送信に成功しました!'
except smtplib.SMTPConnectError, e:
print 'メールの送信に失敗しました。接続エラー: ', e.smtp_code, e.smtp_error
except smtplib.SMTPAuthenticationError, e:
print 'メールの送信に失敗しました。認証エラー: ', e.smtp_code, e.smtp_error
except smtplib.SMTPSenderRefused, e:
print 'メールの送信に失敗しました。送信者が拒否されました: ', e.smtp_code, e.smtp_error
except smtplib.SMTPRecipientsRefused, e:
print 'メールの送信に失敗しました。受信者が拒否されました: ', e.smtp_code, e.smtp_error
except smtplib.SMTPDataError, e:
print 'メールの送信に失敗しました。データエラー: ', e.smtp_code, e.smtp_error
except smtplib.SMTPException, e:
print 'メールの送信に失敗しました。', e.message
except Exception, e:
print 'メールの送信中に例外が発生しました。', str(e)