To send emails with Python using SendGrid, you can use the sendgrid
library.
First, you need to install the library using pip:
# pip install sendgrid
# pip install Mail
Â
import os, sys
import base64
from os import path
import sendgrid Â
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import *
sendgrid_key = #your_sengrid_key_comes_here
to_list = Personalization()
to_list.add_to (Email (“email_address_1”))
to_list.add_to (Email (“email_address_2”))
subject_title = “This is an example email from Mr sososo “
message = Mail(
from_email=’info@africanstudents.net’,
subject=subject_title,
html_content=”””
<p>Dear friends,</p>
<p>I hope you are all enjoying the Python programming bootcamp course. </p>
<p>By now, you should have learnt a lot of good stuff. </p>
<p>Cheers</p>
“””
)
sg = SendGridAPIClient(sendgrid_key)
message.add_personalization(to_list)
response = sg.send(message)
print(‘Email has been sent successfully’)
Â
Â
Replace 'YOUR_SENDGRID_API_KEY'
with your actual SendGrid API key. You can obtain your API key from the SendGrid dashboard.
In this script, we create a SendGridAPIClient
object with our API key. Then, we define the sender, recipient, subject, and content of the email. We create a Mail
object with this information and use the send
method of the SendGridAPIClient
object to send the email.
Make sure to handle any exceptions that may occur during the sending process.
Remember to replace 'sender@example.com'
and 'recipient@example.com'
with the actual email addresses of the sender and recipient. Additionally, you can customize the subject and content of the email according to your requirements.