avatarMarco Santos

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4543

Abstract

">"../sendGrid-API.txt"</span>, <span class="hljs-string">"r"</span>) <span class="hljs-keyword">as</span> f: api_key = f.<span class="hljs-built_in">read</span>()

<span class="hljs-comment"># Using the api key with the sendgrid client</span> sg = SendGridAPIClient(api_key)</pre></div><h1 id="6eeb">3. Set the Email Variables</h1><p id="0ea7">Here you’ll need to set the different variables for your email. The variable names are pretty self-explanatory:</p><div id="a44a"><pre><span class="hljs-attribute">sender</span> <span class="hljs-operator">=</span> <span class="hljs-string">"[email protected]"</span></pre></div><div id="c80d"><pre><span class="hljs-attribute">recipient</span> <span class="hljs-operator">=</span> <span class="hljs-string">"[email protected]"</span></pre></div><div id="e4ce"><pre><span class="hljs-attribute">subject</span> <span class="hljs-operator">=</span> <span class="hljs-string">"Hey Check Out This Test Email!"</span></pre></div><div id="b1f2"><pre><span class="hljs-attribute">content</span> <span class="hljs-operator">=</span> <span class="hljs-string">"I just sent this email with Python. So cool!"</span></pre></div><h1 id="54d9">4. Construct the Email Object</h1><p id="2769">This is where we’ll create the email object from SendGrid. Just use the variables above and assign them to the appropriate parameters:</p><div id="389e"><pre>email = Mail( <span class="hljs-attribute">from_email</span>=sender, <span class="hljs-attribute">to_emails</span>=recipient, <span class="hljs-attribute">subject</span>=subject, <span class="hljs-attribute">html_content</span>=content )</pre></div><h1 id="3c57">5. Send the Email</h1><p id="7aa7">Here we will actually send the email object we constructed above by using the SendGrid client:</p><div id="cb7d"><pre><span class="hljs-attribute">response</span> <span class="hljs-operator">=</span> sg.send(email)</pre></div><div id="5e4c"><pre><span class="hljs-comment"># Printing out the response </span> <span class="hljs-built_in">print</span>(response.status_code)</pre></div><p id="eb19">Print out the response status code in order to know if the email has been accepted and is ready to ship out.</p><p id="c0e0">Additionally, check the recipient’s inbox if you can to see if you’ve received the email.</p><h1 id="edd8">6. Putting It All Together</h1><p id="e4a5">Now in order to make the previous code flow collectively, we’ll combine all the elements above into a single function. With the variables being the only thing we need to adjust. Here’s some code:</p> <figure id="7426"> <div> <div>

            <iframe class="gist-iframe" src="/gist/marcosan93/b5c585bd7407de384cc16733e73a1e4a.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="2d61">By using this function, we would only need to change the email variable details. These details can be changed outside of the function if needed. Below are the new details we can use to test out our newly made function.</p><h2 id="2891">New Variables</h2><div id="f31d"><pre><span class="hljs-comment"># New Variables</span>

<span class="hljs-attr">sender</span> = <span class="hljs-string">"[email protected]"</span></pre></div><div id="2f9a"><pre><span class="hljs-attribute">recipient</span> <span class="hljs-operator">=</span> <span class="hljs-string">"[email protected]"</span></pre></div><div id="f20b"><pre><span class="hljs-attribute">subject</span> <span class="hljs-operator">=</span> <span class="hljs-string">"Hey Check Out This New Test Email!"</span></pre></div><div id="1ae0"><pre><span class="hljs-comment"># With some html formatting</span> <span class="hljs-attr">content</span> = <span class="hljs-string">""" Hey!

&lt;p&gt;I just sent this email by using &lt;b&gt;Python&lt;/b&gt;.&lt;/p&gt; 

&lt;p&gt;&lt;i&gt;It's so cool!&lt;i/&gt;&lt;/p&gt;

"""</span></pre></div><div id="3ca7"><pre># Testing the <span class="hljs-keyword">function</span> <span class="hljs-title">sendMyEmail</span>(sender, recipient, subject, content)</pre></div><p id="219f">The variables above are largely the same except for the content of the message. A great thing about SendGrid's API is that it accepts HTML text formatting. Here we formatted the previous text to include some new HTML tags to make the new test email pop!</p><p id="f5b9">Here’s a quick rundown on the HTML tags we used an

Options

d their effects:</p><ul><li><code><p>text</p></code> — Paragraph spacing.</li><li><code><b>text</b></code> — Bold text.</li><li><code><i>text<i/></code> — Italicize text.</li></ul><p id="9dec">If the function runs perfectly, then you should receive a return message from the code above saying: <code>‘Email has been accepted!’</code></p><h2 id="d046">Checking the email</h2><p id="3e32">And to be more sure of the functionality, you can check the recipient’s email inbox and look for the message you just sent:</p><figure id="437d"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*eEGm1yMqD0wO_zdviZtT5Q.png"><figcaption>The email received from Python using SendGrid</figcaption></figure><h1 id="0df2">7. Sending Emails With Dynamically Changing Variables</h1><p id="2f93">Now that we’ve tested and successfully sent an email, we can move on to some more practical applications of this feature. There are a lot of great applications to be made from a simple function like the one we just created, but let’s stick with something simple but slightly more complex than before.</p><p id="5b3e">In the following code blocks, you will learn how to send multiple emails with a changing subject line, content, and at different times.</p><p id="dd87">First, let’s import a new library that we’ll use to send emails at different time intervals:</p><div id="fd4f"><pre><span class="hljs-keyword">import</span> time</pre></div><p id="a72e">Next, we’ll create a loop that iterates through a shortlist of greetings. This list will be how our email will change with each iteration. In each iteration, the subject and content will adjust based on the list of greetings.</p> <figure id="7390"> <div> <div>

            <iframe class="gist-iframe" src="/gist/marcosan93/258dfaf422b5265aae21718eeda8133f.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="3b81">As you can see in the code above, the greetings affect the subject line and content by altering just one word. At the end of the loop, there is a short period of time of waiting (which you can adjust if wanted) before sending another email again.</p><p id="a8a7">If the loop ran successfully, you should be able to see three different emails in the recipient's inbox:</p><figure id="da2e"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*o96g0CrGKbqf4N_sZ8VWhQ.png"><figcaption>Three emails at three separate times</figcaption></figure><p id="b644">If you see something similar to the image above — excellent! You’ve successfully sent multiple emails with different subject lines and content by using Python!</p><h1 id="259b">Other Use Cases</h1><p id="de4f">The above was just a simple example of what we can do with sending emails with Python. But there are more applications and different approaches that can be expanded upon with this function such as:</p><ul><li>Sending a somewhat personal email to a large mailing list of contacts.</li><li>Schedule an email reminder to be sent to a select group of individuals.</li><li>Send updates and new information automatically.</li><li>Mass marketing campaigns.</li><li>And more…</li></ul><p id="5a10">SendGrid is an awesome tool for a lot of these, and you should <a href="https://github.com/sendgrid/sendgrid-python">read up on the Python documentation</a> to learn more about its features. For example, they already have built-in functionality for sending to multiple individuals.</p><p id="bffa">I hope you’ve learned plenty about the great applications of sending an email with programming and Python. It is a great application to use for any repetitive email tasks you may encounter. Be creative with the application of this function and you will unlock a lot of opportunities to automate your daily tasks!</p><h1 id="d333">Resources</h1><p id="5b19">Check out this <a href="https://github.com/marcosan93/Medium-Misc-Tutorials/blob/main/Send-Emails-with-Python.ipynb">GitHub repository</a> for the full source code. And here’s the complete <a href="https://github.com/sendgrid/sendgrid-python">SendGrid documentation</a>.</p><blockquote id="8669"><p><a href="https://marco-santos.medium.com/membership">Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks!</a></p></blockquote></article></body>

Harness the Power of Python To Send Emails Programmatically

A step-by-step tutorial on sending emails using Python

Photo by Brett Jordan on Unsplash

Programming can be used for a lot of things. From creating simple math functions to building mobile apps. It can also be used to automate specific tasks to be done in seconds, as opposed to doing it yourself which could take hours. As we have developed unique and special ways to utilize code, more and more tasks have become automated. And one of these tasks is — sending emails.

But isn’t sending emails already an easier way of delivering information? Emails did essentially replace physical mail however it still requires some form of manual intervention. These forms are (but are not limited to):

  • Typing up the email
  • Scheduling or knowing when to send the email
  • Determining who is receiving the email

I’m sure there are more, but these are the most obvious ones. Anyways, what if we could automate sending an email with code? Specifically with Python? The applications of such a program can range from scheduled email reminders to mass marketing emails for a company. As you read on, you will learn how to quickly set up a simple Python script to send an email without the need of using an email provider like Gmail.

Choose an Email Service

Not talking about Gmail or yahoo, but an email service with an API. Using such a service will allow you a lot of flexibility to send multiple emails with an easy-to-use API. I’ve found that this is one of the easiest ways to get started with sending an email in Python.

The email service that I use is called SendGrid. It is free to use and easy to set up an account. The free tier plan for the service allows you to send up to 100 emails every day. It’s also developer-friendly with documentation that supports Python. We will be using SendGrid for the rest of this article tutorial.

Getting Started

In order to get started with SendGrid, you’ll need to create a free account. After you’ve done that, follow these steps:

  1. Verify your sender email address — In the dashboard sidebar, go to Settings to Sender Authentication to Single Sender Verification to Create New Sender. Enter the required info, and go to the email inbox to verify the address.
  2. Get the API Key — Go back to Settings to API Key to Create API Key. Get full access and name it. Click Create & View to view and copy the API key for future usage.

And that’s it. If you want to add more email addresses to send from, you’ll need to verify them like before. With the API key and verified email address, you’re ready to get started with the coding.

1. Install SendGrid

Assuming you are using Jupyter notebooks or Jupyter lab, you can install SendGrid directly from Jupyter with the following command:

!pip install sendgrid

Otherwise, you can just do it in your command terminal with the same command above but remove the exclamation mark — pip install sendgrid.

2. Import SendGrid Libraries and Set the API Key

After you’ve installed SendGrid, you can import the libraries within the package:

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

Next, you’ll want to use the API key and assign it to the SendGrid client. You’ll need to keep your API key private. I kept mine in a text file outside of the code to access it for assignment when needed:

# Importing and assigning the api key
with open("../sendGrid-API.txt", "r") as f:
    api_key = f.read()
    
# Using the api key with the sendgrid client
sg = SendGridAPIClient(api_key)

3. Set the Email Variables

Here you’ll need to set the different variables for your email. The variable names are pretty self-explanatory:

recipient = "[email protected]"
subject = "Hey Check Out This Test Email!"
content = "I just sent this email with Python. So cool!"

4. Construct the Email Object

This is where we’ll create the email object from SendGrid. Just use the variables above and assign them to the appropriate parameters:

email = Mail(
    from_email=sender,
    to_emails=recipient,
    subject=subject,
    html_content=content
)

5. Send the Email

Here we will actually send the email object we constructed above by using the SendGrid client:

response = sg.send(email)
# Printing out the response 
print(response.status_code)

Print out the response status code in order to know if the email has been accepted and is ready to ship out.

Additionally, check the recipient’s inbox if you can to see if you’ve received the email.

6. Putting It All Together

Now in order to make the previous code flow collectively, we’ll combine all the elements above into a single function. With the variables being the only thing we need to adjust. Here’s some code:

By using this function, we would only need to change the email variable details. These details can be changed outside of the function if needed. Below are the new details we can use to test out our newly made function.

New Variables

# New Variables
sender = "[email protected]"
recipient = "[email protected]"
subject = "Hey Check Out This New Test Email!"
# With some html formatting
content = """
    Hey!
    
    <p>I just sent this email by using <b>Python</b>.</p> 
    
    <p><i>It's so cool!<i/></p>
"""
# Testing the function
sendMyEmail(sender, recipient, subject, content)

The variables above are largely the same except for the content of the message. A great thing about SendGrid's API is that it accepts HTML text formatting. Here we formatted the previous text to include some new HTML tags to make the new test email pop!

Here’s a quick rundown on the HTML tags we used and their effects:

  • <p>text</p> — Paragraph spacing.
  • <b>text</b> — Bold text.
  • <i>text<i/> — Italicize text.

If the function runs perfectly, then you should receive a return message from the code above saying: ‘Email has been accepted!’

Checking the email

And to be more sure of the functionality, you can check the recipient’s email inbox and look for the message you just sent:

The email received from Python using SendGrid

7. Sending Emails With Dynamically Changing Variables

Now that we’ve tested and successfully sent an email, we can move on to some more practical applications of this feature. There are a lot of great applications to be made from a simple function like the one we just created, but let’s stick with something simple but slightly more complex than before.

In the following code blocks, you will learn how to send multiple emails with a changing subject line, content, and at different times.

First, let’s import a new library that we’ll use to send emails at different time intervals:

import time

Next, we’ll create a loop that iterates through a shortlist of greetings. This list will be how our email will change with each iteration. In each iteration, the subject and content will adjust based on the list of greetings.

As you can see in the code above, the greetings affect the subject line and content by altering just one word. At the end of the loop, there is a short period of time of waiting (which you can adjust if wanted) before sending another email again.

If the loop ran successfully, you should be able to see three different emails in the recipient's inbox:

Three emails at three separate times

If you see something similar to the image above — excellent! You’ve successfully sent multiple emails with different subject lines and content by using Python!

Other Use Cases

The above was just a simple example of what we can do with sending emails with Python. But there are more applications and different approaches that can be expanded upon with this function such as:

  • Sending a somewhat personal email to a large mailing list of contacts.
  • Schedule an email reminder to be sent to a select group of individuals.
  • Send updates and new information automatically.
  • Mass marketing campaigns.
  • And more…

SendGrid is an awesome tool for a lot of these, and you should read up on the Python documentation to learn more about its features. For example, they already have built-in functionality for sending to multiple individuals.

I hope you’ve learned plenty about the great applications of sending an email with programming and Python. It is a great application to use for any repetitive email tasks you may encounter. Be creative with the application of this function and you will unlock a lot of opportunities to automate your daily tasks!

Resources

Check out this GitHub repository for the full source code. And here’s the complete SendGrid documentation.

Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks!

Programming
Coding
Python
Automation
Data Science
Recommended from ReadMedium