Pythonと電子メール配信の統合

Pythonを使用して、電子メール配信サービスを使用して電子メールを送信します。

Pythonを使用すると、電子メール配信を使用して電子メールを送信できます。電子メールを送信する前に、Pythonで電子メール配信を構成する必要があります。

重要

これらの手順には、便宜上サンプル・コードが含まれており、参照用として使用する必要があります。クライアント・サポートについては、Pythonに連絡する必要があります。これらのステップは、Oracle Linux Serverリリース7.9のコンピュート・インスタンスとPython 3.6でテストされました。これらのステップは、Oracle Linuxインスタンスにログインしていることを想定としています。Linuxのその他のディストリビューションには、異なるコマンドおよびファイルの場所が含まれることがあります。Javaアプリケーション(JavaMailを含む)を最新バージョンに更新して、最新のプロトコル、暗号およびセキュリティ・パッチがOracleでサポートされているセキュリティ・ポリシーおよび暗号に準拠していることを確認する必要があります。

電子メール配信を介した電子メール送信のためのPythonの構成

Pythonで電子メール配信の構成をテストできるようにするには:

  1. 電子メール配信が電子メールを送信するように構成されていることを確認します。開始を参照してください。
    ノート

    電子メール配信を使用するようにPythonを構成するには、SMTP資格証明が必要です。SMTP資格証明の生成時には、ユーザー名とパスワードを書き留めてください。
  2. Pythonがインストールされていることを確認してください。インストール・プロセスは、使用しているオペレーティング・システムによって異なります。たとえば、次のコマンドを実行してOracle LinuxにPythonをインストールします:
    sudo yum install python3 -y
  3. viなどのファイル・エディタで、pythonスクリプトを作成して電子メール配信をテストします。

    次のコマンドを実行します。

    sudo vi ociemail.py
  4. ociemail.pyファイルで、変数を独自の値に置き換えます。
    例:
    # python script for sending SMTP configuration with Oracle Cloud Infrastructure Email Delivery
    import smtplib 
    import email.utils
    from email.message import EmailMessage
    import ssl
    
    # Replace sender@example.com with your "From" address.
    # This address must be verified.
    # this is the approved sender email
    SENDER = 'sender@example.com'
    SENDERNAME = 'Sender Name'
     
    # Replace recipient@example.com with a "To" address. If your account
    # is still in the sandbox, this address must be verified.
    RECIPIENT = 'recipient@example.com'
     
    # Replace the USERNAME_SMTP value with your Email Delivery SMTP username.
    USERNAME_SMTP = 'ocid1.user.oc1..<unique_ID>@ocid1.tenancy.oc1..<unique_ID>.vf.com'
     
    # Put the PASSWORD value from your Email Delivery SMTP password into the following file.
    PASSWORD_SMTP_FILE = 'ociemail.config'
     
    # If you're using Email Delivery in a different region, replace the HOST value with an appropriate SMTP endpoint.
    # Use port 25 or 587 to connect to the SMTP endpoint.
    HOST = "smtp.us-ashburn-1.oraclecloud.com"
    PORT = 587
     
    # The subject line of the email.
    SUBJECT = 'Email Delivery Test (Python smtplib)'
     
    # The email body for recipients with non-HTML email clients.
    BODY_TEXT = ("Email Delivery Test\r\n"
                 "This email was sent through the Email Delivery SMTP "
                 "Interface using the Python smtplib package."
                )
     
    # The HTML body of the email.
    BODY_HTML = """<html>
    <head></head>
    <body>
      <h1>Email Delivery SMTP Email Test</h1>
      <p>This email was sent with Email Delivery using the
        <a href='https://www.python.org/'>Python</a>
        <a href='https://docs.python.org/3/library/smtplib.html'>
        smtplib</a> library.</p>
    </body>
    </html>"""
    
    # get the password from a named config file ociemail.config
    with open(PASSWORD_SMTP_FILE) as f:
        password_smtp = f.readline().strip()
    
    # create message container
    msg = EmailMessage()
    msg['Subject'] = SUBJECT
    msg['From'] = email.utils.formataddr((SENDERNAME, SENDER))
    msg['To'] = RECIPIENT
    
    # make the message multi-part alternative, making the content the first part
    msg.add_alternative(BODY_TEXT, subtype='text')
    # this adds the additional part to the message
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    msg.add_alternative(BODY_HTML, subtype='html')
    
    # Try to send the message.
    try: 
        server = smtplib.SMTP(HOST, PORT)
        server.ehlo()
        # most python runtimes default to a set of trusted public CAs that will include the CA used by OCI Email Delivery.
        # However, on platforms lacking that default (or with an outdated set of CAs), customers may need to provide a capath that includes our public CA.
        server.starttls(context=ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cafile=None, capath=None))
        # smtplib docs recommend calling ehlo() before & after starttls()
        server.ehlo()
        server.login(USERNAME_SMTP, password_smtp)
        # our requirement is that SENDER is the same as From address set previously
        server.sendmail(SENDER, RECIPIENT, msg.as_string())
        server.close()
    # Display an error message if something goes wrong.
    except Exception as e:
        print(f"Error: {e}")
    else:
        print("Email successfully sent!")
    ノート

    Python 2およびレガシー電子メールAPIは、電子メール配信では使用しないでください。
  5. viなどのファイル・エディタで、SMTPパスワードを含むファイルを作成します。次のコマンドを実行し、内容をSMTPパスワードに置き換えます:
    sudo vi ociemail.config
  6. Pythonを使用してテスト電子メールを送信するには、スクリプトが存在しているディレクトリから次のコマンドを実行します:
    python3 ociemail.py

詳細情報

Pythonスクリプトのその他の例は、GitHubにあります。