Integrazione di Python con il servizio di consegna tramite e-mail

Utilizza Python per inviare e-mail tramite il servizio di consegna tramite e-mail.

Puoi utilizzare Python per inviare e-mail tramite il servizio di consegna tramite e-mail. Prima di poter inviare e-mail, è necessario configurare il servizio di consegna tramite e-mail in Python.

Importante

Queste istruzioni contengono un codice di esempio che può essere utilizzato come riferimento. Per il supporto client, è necessario contattare Python. Questi passi sono stati testati su un'istanza di computazione Oracle Linux Server release 7.9 e su Python 3.6. Questi passi presuppongono che l'utente abbia eseguito il login a un'istanza Oracle Linux. Altre distribuzioni di Linux possono avere diversi comandi e posizioni di file. Le applicazioni Java (incluso JavaMail) devono essere aggiornate alla versione più recente per garantire che i protocolli, le cifrazioni e le patch di sicurezza più recenti siano conformi ai criteri e alle cifrature di sicurezza supportati da Oracle.

Configurare Python per inviare e-mail tramite il servizio di consegna tramite posta elettronica

Per consentire a Python di eseguire il test della configurazione del servizio di consegna tramite e-mail:

  1. Assicurarsi che Consegna tramite e-mail sia configurato per l'invio di e-mail. Vedere Guida introduttiva.
    Nota

    Le credenziali SMTP sono necessarie per configurare Python in modo che utilizzi il servizio di consegna tramite e-mail. Assicurarsi di prendere nota del nome utente e della password quando si generano le credenziali SMTP.
  2. Assicurarsi che Python sia installato. Il processo di installazione varia a seconda del sistema operativo in uso. Ad esempio, eseguire il seguente comando per installare Python su Oracle Linux:
    sudo yum install python3 -y
  3. In un editor di file come vi, creare uno script python per eseguire il test del servizio di consegna tramite posta elettronica.

    Eseguire il comando riportato di seguito:

    sudo vi ociemail.py
  4. Nel file ociemail.py sostituire le variabili con valori personalizzati.
    Ad esempio:
    # 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 465 to connect to the SMTP endpoint.
    HOST = "smtp.us-ashburn-1.oraclecloud.com"
    PORT = 465
     
    # 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_SSL(HOST, PORT)
        # if using port 25 or 587, comment out the line above and uncomment the line below:
        # 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.
        # If using port 25 or 587, uncomment the line below:
        # 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!")
    Nota

    • Per utilizzare Python con la porta 25 o 587, modificare smtplib.SMTP_SSL(HOST, PORT) in smtplib.SMTP(HOST, PORT).
    • Le API di posta elettronica Python 2 e legacy non devono essere utilizzate con il servizio di consegna tramite e-mail.
  5. In un editor di file, ad esempio vi, creare un file contenente la password SMTP. Eseguire il comando seguente e sostituire il contenuto con la password SMTP:
    sudo vi ociemail.config
  6. Per inviare un'e-mail di test con Python, eseguire il comando seguente dalla directory in cui si trova lo script:
    python3 ociemail.py

Ulteriori informazioni

Altri esempi di script Python sono disponibili in GitHub.