Oracle Cloud Infrastructure Email Delivery: step-by-step instructions for sending emails

Simple Mail Transfer Protocol (SMTP) relay and email sending service Oracle Cloud Infrastructure (OCI) Email Delivery offers a quick and dependable managed solution for sending transactional and large-volume bulk emails. For mission-critical communications like receipts, fraud detection alerts, multi-factor identity verification, and password resets, Email Delivery offers the tools required to send application-generated email. In this blog, I walk you through the email delivery process and provide background information on email authentication and best practices.

Oracle Cloud Infrastructure

Is email delivery right for you?

Every cloud-based app or business aiming to reach users’ inboxes affordably should leverage Email Delivery. Our service eliminates the hassle and cost of building an in-house solution, offering scalability, affordability, and reliability. Consider Oracle Cloud Infrastructure Email Delivery as a comparable service if you presently use SendGrid or Amazon Simple Email Service (SES).

The best part is that it’s easy to set up and use!

Required conditions

Access to an Oracle Cloud Infrastructure environment is a prerequisite. If you don’t already have one, it’s simple to start one with US$300 in free credits and access to our always-free services.

Ensure that the user is assigned to a group with authority to oversee email-family resources within your environment. For security purposes, creating a new user is recommended over utilizing the Console user with pre-existing permissions. To create a group and give it the necessary permissions, go to the documentation’s “Set Up Permissions” section if you need assistance.

Lastly, in order to publish your sender policy framework (SPF) and domain keys identified mail (DKIM) entries, you need a DNS domain. Sending emails doesn’t require DKIM or SPF, but we strongly advise configuring these. Later on, we delve more into DKIM and SPF.

Email sending: Create SMTP credentials

To send emails using Email Delivery, you need to have your SMTP credentials. There can only be a maximum of two SMTP credentials per user. Therefore, add a new user if you require more than two.

Go to User Settings after logging into the Oracle Cloud Console.

Oracle Cloud Infrastructure
Figure 1: Navigating to user settings

To create an SMTP credential, scroll down and click on it.

Figure 2: Generating SMTP credentials​​​​​

Make a copy of the password and username. After dismissing the dialog box, you are unable to get the password back for security reasons.

Oracle Cloud Infrastructure
Figure 3: Copying the password and username for an SMTP credential

Configure your email domain.

You can configure crucial authentication procedures for email sending with an email domain. Choose Email Delivery and Application Integration under Developer Services. To create a domain, click Email Domains. Select a DNS domain that you own or manage and intend to use for the sending email address when configuring DKIM and SPF.

Oracle Cloud Infrastructure
Figure 4: My email domain

Configure DKIM

By using DKIM, an email authentication method, the recipient can confirm who owns an email domain. It adds a digital signature to the email, which is a header field with all the key-fetching information and the signature. Email clients, such as Microsoft and Gmail, recognize the DKIM signature and use a DNS query to look up the domain’s public key. Upon discovery, the signature undergoes decryption and verification to ascertain its creation with the corresponding private key. Thus, using DKIM can safeguard your domain from malicious emails sent on its behalf as well as enhance email deliverability.

Now that you are familiar with DKIM, navigate to it in your zone and create an account.

Oracle Cloud Infrastructure
Figure 5: Navigating to DKIM

For this DKIM key, which needs to be globally unique for your domain, we employ the DKIM selector. To aid in future key rotation, we advise including a date portion and regional indicator in the selector, such as prefix-region: YYYYMMDD. After creating the DKIM record, select Create DKIM.

Oracle Cloud Infrastructure
Figure 6: Creating DKIM record

The immediate configuration of our DNS domain is necessary. Proceed to your zone and use the value it provides to create the CNAME record.

Oracle Cloud Infrastructure
Figure 7: Creating DKIM CNAME record

If successful, the DKIM signature status transitions to Active. It took me about a minute for mine to spread.

Updates to your DNS records may take up to 24 hours to propagate worldwide, depending on the type of change.

Figure 8: DKIM signing status

Make sure to rotate your DKIM keys every six months or so. Rotation lessens the possibility that attackers will be able to steal or crack active keys. See M3AAWG DKIM Key Rotation Best Common Practices for additional details on key rotation and DKIM in general.

Create a sender that has been authorized.

When sending mail using Oracle Cloud Infrastructure, all “from” addresses require an approved sender. The mail is returned otherwise. To use an email address for email delivery, the sender must register it.

Take note of the information below concerning authorized senders:

  • An approved sender is linked to a compartment, confined within the area where it was established. You cannot send email through the US East (Ashburn) area using an approved sender that you create in the US West (Phoenix) region.
  • Keep authorized senders out of the root compartment. If so, you must establish a policy to oversee authorized senders for the duration of the lease. The policy can be compartment-specific when approved senders are created in a compartment other than the root.
  • Using more than one address in the email “From:” header isn’t advisable, as it raises the risk of message deletion or being marked as spam. For optimal results with Email Delivery, align the “From:” address with the header “From:” address to avoid compromising email performance due to unapproved sender addresses.
  • Tenancy-specific approved senders are distinct. A 409 conflict error is returned by the service if you establish a duplicate sender.

You can see approved senders under DKIM. Make one.

Oracle Cloud Infrastructure
Figure 9: Creating an Approved Sender

Set up SPF for your authorized sender domain.

By specifying allowed email servers via SPF, email spoofing is deterred. This practice involves adding a unique TXT record to your domain’s DNS records. Receiving mail servers then verify the originating IP’s permission to send from that domain by consulting the sender’s SPF record. Without SPF, spam or phishing emails may appear to be from a trusted domain.

Locate the sender you have authorized. Click the three dots and choose View SPF.

Figure 10: Viewing SPF record values

After deciding on your transmitting location, set up a DNS TXT record with the appropriate value. Americas is what I’m using.

Oracle Cloud Infrastructure
Figure 11: Creating SPF TXT record

Although it can take some time, DKIM signing and SPF are now operational on your domain.

Oracle Cloud Infrastructure
Figure 12: DKIM and SPF working

Set up the email protocol.

To configure the connection in your system, navigate to Configuration and access SMTP sending information.

Figure 13: SMTP sending information

The data shown is as follows:

  • Open destination: The public email address that is utilized in this area
  • SMTP ports: The email-accepting SMTP ports. TLS is supported by Email Delivery on port 25 or 587 (strongly advised).
  • Security: Shows whether TLS is in use. Email delivery requires customers to encrypt emails while they are in transit.

Send Mail

We can start sending mail now that our email domain has been set up and secured! You can make use of an SMTP library or product of your own, like Sendmail or Postfix. I’ll give you an example using a basic Python script. The documentation contains information on using Python for testing.

The skeleton code is displayed in the code block below:

# Python script for using Oracle Cloud Infrastructure Email Delivery to deliver SMTP configuration

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
# has not been confirmed; it is still in the sandbox.
RECIPIENT = 'recipient@example.com'
 
# Replace the USERNAME_SMTP value with your Email Delivery SMTP username.
USERNAME_SMTP = 'ocid1.user.oc1..@ocid1.tenancy.oc1...vf.com'
 
# Fill in the following file using the PASSWORD value that comes with your Email Delivery SMTP password.
PASSWORD_SMTP_FILE = 'ociemail.config'
 
# Use an appropriate SMTP endpoint in place of the HOST value if you're utilizing Email Delivery in a different region.
# To connect to the SMTP endpoint, use port 25 or 587.
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 users whose email clients do not support HTML.
BODY_TEXT = (
             "This email has been transmitted via the Email Delivery SMTP service"
             "Interface using the Python smtplib package."
            )
 
# Retrieve the password from an OCIemail.config file with a designated name
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')

# Try to send the message.
try: 
    server = smtplib.SMTP(HOST, PORT)
    server.ehlo()
    The CA that OCI Email Delivery uses is among the trusted public CAs that the majority of Python runtimes default to.
    # Customers might have to supply a capath that includes our public CA, though, if their platform doesn't have that default or has an out-of-date collection of CAs.
    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)
# We need the SENDER to match the previously specified FROM address.
    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!")

The code, ociemail.py, is displayed in the following block:

# Python script for using Oracle Cloud Infrastructure Email Delivery to deliver SMTP configuration
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 = 'BlogTestSender@elcaroydoc.com'
SENDERNAME = 'Blog Test Sender'
 
# Replace recipient@example.com with a "To" address. If your account


# needs to be validated; it's still in the sandbox.
RECIPIENT = 'cody.brinkman@oracle.com'
 
# Replace the USERNAME_SMTP value with your Email Delivery SMTP username.
USERNAME_SMTP = 'my_smtp_credential_username'
 


# Fill in the following file using the PASSWORD value that comes with your Email Delivery SMTP password.
PASSWORD_SMTP_FILE = 'ociemail.config'
 


# Use an appropriate SMTP endpoint in place of the HOST value if you're utilizing Email Delivery in a different region.
# To connect to the SMTP endpoint, use port 25 or 587.
HOST = "smtp.us-ashburn-1.oraclecloud.com"
PORT = 587
 
# The subject line of the email.
SUBJECT = 'Email Delivery Blog Test'
 


# The email body for users of email clients that are not HTML-capable.
BODY_TEXT = (
             "This email has been transmitted via the Email Delivery SMTP service "
             "Interface using the Python smtplib package."
            )
 
# Retrieve 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')

# Try to send the message.
try: 
    server = smtplib.SMTP(HOST, PORT)
    server.ehlo()
    

The CA that OCI Email Delivery uses is among the trusted public CAs that the majority of Python runtimes default to.
    # Customers might have to supply a capath that includes our public CA, though, if their platform doesn't have that default or has an out-of-date collection of CAs.
    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)


# We need the SENDER to match the previously specified FROM address.
    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!")

I made a file called ociemail.config in the same directory, and it has my password for my SMTP credential. To initiate the script, utilize the subsequent command:

python3 ociemail.py
Figure 14: Running script
FIgure 15: Email received

A list of suppressions

Additionally, the suppression list is visible under Email Delivery. Emails that are not receiving any messages from Email Delivery are included in this list. Email Delivery automatically adds email addresses with bounce codes indicating persistent failures or user complaints to the suppression list as soon as you start sending emails in order to safeguard your sender reputation. Click Add Suppression to manually add email addresses to your suppression list.

Volume evaluation

When testing at scale, adhere to the following best practices to preserve the reputation of both your sender and ours:

  • Make use of a discard.oracle.com domain reception address, such example@discard.oracle.com. The mail is accepted by email delivery; however, it is not delivered to an inbox.
  • When a lot of emails are sent to legitimate addresses, the recipients reject them, which leads to a lot of hard bounces. IP reputation is negatively impacted by this outcome. Send a limited number of emails to an invalid domain to test bounce processing.

Conclusion

Oracle Cloud Infrastructure Email Delivery is a ready-to-use, developer-friendly solution that addresses infrastructure, security, authentication, and configuration problems for email delivery. As you increase the volume and frequency of outgoing emails, Email Delivery makes sure that emails get to user inboxes, which is essential for any company that wants to communicate with its clients. This service is perfect for transactional, application-generated emails and is available in all OCI realms and regions. We observed how simple it is to set up our email domain, approve the sender, and test everything with a straightforward Python script. Consult the official documentation for further details and illustrations.

Oracle Cloud Infrastructure gives developers the enterprise features they need to create cutting-edge cloud apps. I suggest using the Oracle Cloud Free Tier, which offers a 30-day free trial with US$300 in credits, if you wish to check out this blog for free. In addition, Free Tier offers a number of “always-free” services that remain active even after your free credits run out.