すべてのプロダクト
Search
ドキュメントセンター

Alibaba Mail:Python 3.6 以降を使用した SMTP メール送信のコード例

最終更新日:Aug 26, 2026

このトピックでは、Python 3.6 以降を使用して SMTP メールを送信するコード例を説明します。

Alibaba Mail の設定

SMTP サーバーアドレス:

Singapore サイト: smtp.sg.aliyun.com

China (Hong Kong) サイト: smtp.hk.aliyun.com

Germany サイト: smtp.de.alibabacloud.com

US サイト: smtp.us.alibabacloud.com

ポート: 暗号化されていない接続の場合は 25、SSL 暗号化接続の場合は 465


# -*- coding:utf-8 -*-
import smtplib
import email
# import json
# import base64
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
from email.utils import formataddr

# import urllib.request
# import ssl

# ユーザー名
username = 'XXXXXXXX'
# パスワード。サードパーティクライアントのセキュリティパスワードを有効にした場合は、Web ページで生成されたセキュリティパスワードを使用します。それ以外の場合は、ログインパスワードを使用します。
password = 'XXXXXXXX'
# カスタム Reply-to アドレス
replyto = 'XXXXXXXX'
# 表示される To 受信者アドレス
rcptto = ['address1@example.net', 'address2@example.net']
# 表示される Cc 受信者アドレス
rcptcc = ['address3@example.net', 'address4@example.net']
# Bcc 受信者アドレス。Bcc 受信者はメールには表示されませんが、受信は可能です。
rcptbcc = ['address5@example.net', 'address6@example.net']
receivers = rcptto + rcptcc + rcptbcc

# alternative 構造の構築
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('カスタムメールの件名')
msg['From'] = formataddr(["カスタム送信者のニックネーム", username])  # ニックネーム + 送信者アドレス (または代理送信アドレス)
# リストを文字列に変換
msg['To'] = ",".join(rcptto)
msg['Cc'] = ",".join(rcptcc)
msg['Reply-to'] = replyto  # 返信メールの受信に使用します。受信者側での標準プロトコルのサポートが必要です。
msg['Return-Path'] = 'test@example.net'  # バウンスメールの受信に使用します。受信者側での標準プロトコルのサポートが必要です。
msg['Message-id'] = email.utils.make_msgid()  # message-id は各メールを一意に識別します。その形式は RFC 5322 に準拠する必要があります。通常、 のような形式になります。uniquestring はメールサーバーによって生成される一意の識別子で、タイムスタンプや乱数などの情報が含まれる場合があります。
msg['Date'] = email.utils.formatdate()


# alternative 構造の text/plain パートの構築
# textplain = MIMEText('カスタムプレーンテキストパート', _subtype='plain', _charset='UTF-8')
# msg.attach(textplain)

# alternative 構造の text/html パートの構築
texthtml = MIMEText('カスタム HTML ハイパーテキストパート', _subtype='html', _charset='UTF-8')
msg.attach(texthtml)

# # ローカルの添付ファイルを送信
# files = [r'C:\Users\Downloads\test1.jpg', r'C:\Users\Downloads\test2.jpg']
# for t in files:
#     filename = t.rsplit('/', 1)[1]
#     part_attach1 = MIMEApplication(open(t, 'rb').read())  # 添付ファイルを開く
#     part_attach1.add_header('Content-Disposition', 'attachment', filename=filename)  # 添付ファイルに名前を付ける
#     msg.attach(part_attach1)  # 添付ファイルを追加

# # URL から添付ファイルを送信
# files = [r'https://example.oss-cn-shanghai.aliyuncs.com/xxxxxxxxxxx.png']
# for t in files:
#     filename=t.rsplit('/', 1)[1]
#     response = urllib.request.urlopen(t)
#     part_attach1 = MIMEApplication(response.read())  # 添付ファイルを開く (ローカルファイルではない)
#     part_attach1.add_header('Content-Disposition', 'attachment', filename=filename)  # 添付ファイルに名前を付ける
#     msg.attach(part_attach1)  # 添付ファイルを追加


# メールを送信
try:
    # SSL 暗号化を使用するには、次のようにクライアントを作成します
    # client = smtplib.SMTP_SSL('smtp.sg.aliyun.com', 465)

    # Python 3.10/3.11 で SSL ハンドシェイクが失敗した場合は、次のように処理します:
    # ctxt = ssl.create_default_context()
    # ctxt.set_ciphers('DEFAULT')
    # client = smtplib.SMTP_SSL('smtp.sg.aliyun.com', 465, context=ctxt)

    # 標準の SMTP ポートは 25 です
    client = smtplib.SMTP('smtp.sg.aliyun.com', 25, timeout=10)
    # DEBUG モードを有効化
    # client.set_debuglevel(0)
    # 送信者アドレスと認証アドレスは同じである必要があります
    client.login(username, password)
    # 注意: DATA コマンドの戻り値を取得するには、smtplib の sendmail カプセル化メソッドを参照してください:
    # SMTP.mail/SMTP.rcpt/SMTP.data メソッドを使用
    # print(receivers)
    client.sendmail(username, receivers, msg.as_string())  # 複数の受信者がサポートされています。具体的な制限については、仕様チェックリストを参照してください。
    client.quit()
    print('メールの送信に成功しました。')
except smtplib.SMTPConnectError as e:
    print('メールの送信に失敗しました。接続に失敗しました: ', e.smtp_code, e.smtp_error)
except smtplib.SMTPAuthenticationError as e:
    print('メールの送信に失敗しました。認証エラー: ', e.smtp_code, e.smtp_error)
except smtplib.SMTPSenderRefused as e:
    print('メールの送信に失敗しました。送信者が拒否されました: ', e.smtp_code, e.smtp_error)
except smtplib.SMTPRecipientsRefused as e:
    print('メールの送信に失敗しました。受信者が拒否されました: ', e.smtp_code, e.smtp_error)
except smtplib.SMTPDataError as e:
    print('メールの送信に失敗しました。データ受信が拒否されました: ', e.smtp_code, e.smtp_error)
except smtplib.SMTPException as e:
    print('メールの送信に失敗しました: ', str(e))
except Exception as e:
    print('メール送信で例外が発生しました: ', str(e))