Oracle Cloud: Email Delivery using Python
Tags: oracle, email, python
Published: 2023-06-06 02:13:48

_How to send an email through the Oracle Cloud Email Delivery service via Python’s email package_

This tutorial continues from our last article: [Oracle Cloud: Email Delivery using Mailx](https://dev.to/farisdurrani/oracle-cloud-email-delivery-using-mailx-2kac) and will adopt the same initial steps but instead of using Mailx, will use Python.

The Oracle Cloud Infrastructure provides an [Email Delivery](https://www.oracle.com/cloud/networking/email-delivery/) service that enables users to send bulk emails to their recipients. The official documentation to get started lies [here](https://docs.oracle.com/en-us/iaas/Content/Email/Reference/gettingstarted.htm).

This tutorial lays out the basic steps to accomplishing email sending using this service via Mailx referencing the official tutorial and this blog: [Step-by-step instructions to send email with OCI Email Delivery](https://blogs.oracle.com/cloud-infrastructure/post/step-by-step-instructions-to-send-email-with-oci-email-delivery).

## Cost

From that same website, we see the current cost of sending emails. The [FAQ](https://www.oracle.com/cloud/networking/email-delivery/faq/) states one email is equivalent to 2 MB or one recipient in the To, CC, or BCC fields.

![Screenshot of Oracle Cloud website that shows the current price of the email delivery at $0.00 for the first 3100 emails and $0.085 for every 1000 emails above that](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uwjd1bnpi78nkataju25.png)

_Screenshot of Oracle Cloud website that shows the current price of the email delivery at $0.00 for the first 3100 emails and $0.085 for every 1000 emails above that_

## Set up Email Delivery service on OCI

First, you need to set up the Email Delivery service on OCI.

1.  Create an SMTP Credential. Click your profile picture and click **Generate credentials** in **SMTP credentials**. Make sure to save the user and password info:

![Screenshot - OCI SMTP Credentials page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c5k2oab5qtj2t2t8lpp3.png)


![OCI created SMTP credentials confirmation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jfnddoszz641zdm6a5yb.png)

2\. Go to the Email Delivery service

![Searching for Email Delivery in OCI console search bar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6tac38jl368rzmr0zoe8.png)

3\. Create an Approved Sender using an email in a server you control or a random email that may not even exist (I use fdurrani@ulhqlkypwzshkgqhwqfb.com which does not exist). This will be your From email.

Note that sending emails from unverified domains may lead to email bounces, quarantine, or restrictions of the recipient from receiving your email:

![OCI create approved sender textbox](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k9l0tozx8cx8qj8bmiux.png)

4\. Navigate to the Configuration tab of Email Delivery and copy the information on the page:

![OCI Email Delivery configuration page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6jqj0a7sptbtxxdqmyu6.png)

## Send email

Copy paste the following Python code (adapted from the linked blog post), replacing the `SENDER`, `RECIPIENT`, `USERNAME_SMTP`, `HOST`, `PORT`, and `password_smtp` with your own.

```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 = 'fdurrani@ulhqlkypwzshkgqhwqfb.com'
SENDERNAME = 'Blog Test Sender'
 
# Replace recipient@example.com with a "To" address. If your account
# is still in the sandbox, this address must be verified.
RECIPIENT = 'fdurrani@mythics.com'
 
# Replace the USERNAME_SMTP value with your Email Delivery SMTP username.
USERNAME_SMTP = 'ocid1.user.oc1..aaaaaaaaaznjxw5fvpuizguxf5avbsje6sbta7j53oh3gyhiorp73fq@ocid1.tenancy.oc1..aaaaaaaaaeve7ubmplo4cxobeukpwp2uaiuusekfkut3hcvblaanpa.go.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.email.us-ashburn-1.oci.oraclecloud.com"
PORT = 587
 
# The subject line of the email.
SUBJECT = 'Email Delivery Blog Test'
 
# The email body for recipients with non-HTML email clients.
BODY_TEXT = (
             "This email was sent through the Email Delivery SMTP "
             "Interface using the Python smtplib package."
            )
 
# get the password from a named config file ociemail.config
# with open(PASSWORD_SMTP_FILE) as f:
password_smtp = '0jfpB;uQpAjh_u!a'

# 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')

# 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!")
```

Run the file:

![Terminal showing success message after running the Python script](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60l64wxjfj2e9c0csjdo.png)

And see the email in your inbox (ignore the CAUTION line that was automatically added):


![Outlook showing received email](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kpdijd4csv9dntitwspx.png)


---

## References

1.  [Step-by-step instructions to send email with OCI Email Delivery](https://blogs.oracle.com/cloud-infrastructure/post/step-by-step-instructions-to-send-email-with-oci-email-delivery)
2.  [Oracle Email Delivery](https://www.oracle.com/cloud/networking/email-delivery/)

***Safe harbor statement***
The information provided on this channel/article/story is solely intended for informational purposes and cannot be used as a part of any contractual agreement. The content does not guarantee the delivery of any material, code, or functionality, and should not be the sole basis for making purchasing decisions. The postings on this site are my own and do not necessarily reflect the views or work of Oracle or Mythics, LLC.

*This work is licensed under a [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by/4.0/).*