Skip to content

Instantly share code, notes, and snippets.

@jackcoldrick90
Created August 7, 2023 22:51
Show Gist options
  • Save jackcoldrick90/a87c7665d5959f01178bf5d30e09ea05 to your computer and use it in GitHub Desktop.
Save jackcoldrick90/a87c7665d5959f01178bf5d30e09ea05 to your computer and use it in GitHub Desktop.
Transactional Email #2 - SMTP API
import requests
import urllib
import json
import smtplib
import os
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
#1. CREATE THE TOKEN
# This function is used to create the token. This will provide us with the credentials required access our SMTP servers.
# It takes 3 arguments, who the token is created by, the name of the token and whether or not we want the token to create new contacts.
# You'll also notice an "Authorization" header. You must use oAuth in order to authenticate and generate a token via our API.
def create_smtp_api_token(created_by, campaign_name, create_contact):
data = json.dumps({
"createdBy": created_by,
"campaignName": campaign_name,
"createContact": create_contact
})
r = requests.post("https://api.hubapi.com/marketing/v3/transactional/smtp-tokens" , data, headers={"content-type": "application/json", "Authorization": "Bearer {{YOUR_ACCESS_TOKEN}}"})
if 200 <= r.status_code < 300:
return r.json()
else:
raise Exception("Unknown error with HubSpot API: code:{0}, response:{1}".format(r.status_code, r.content))
#2. SET VARIABLES
# Here we define who we want to send the email from and who we wish to send the email to. We also specify additional components of the email
# for instance the subject line and the body.
FROM_EMAIL = "{{YOUR_EMAIL_ADDRESS}}"
TO_EMAIL = "{{RECIPIENTS_EMAIL_ADDRESS}}"
SUBJECT = "SMTP API - Test Email w. attachment"
MESSAGE = "This is a test email send using HubSpots SMTP API. You'll notice it includes an attachment"
#3. SEND EMAIL
# This function takes the SMTP token we generated and connects to the HubSpot SMTP server to trigger the send of the email.
# notice how we use the variables above to specify the subject and the body of the email itself.
def send_test_email(smtp_api_token):
img_data = open("hubspot.png", 'rb').read()
server = smtplib.SMTP("smtp.hubapi.com", 587)
server.starttls()
server.login(smtp_api_token['id'], smtp_api_token['password'])
msg = MIMEMultipart()
msg['Subject'] = SUBJECT
msg['From'] = FROM_EMAIL
msg['To'] = TO_EMAIL
text = MIMEText(MESSAGE)
msg.attach(text)
image = MIMEImage(img_data, name=os.path.basename("hubspot.png"))
msg.attach(image)
server.sendmail(FROM_EMAIL, TO_EMAIL, msg.as_string())
server.quit()
print ("Enqueued email")
#4. CALL THE FUNCTIONS
smtp_api_token = create_smtp_api_token("{{YOUR_NAME}}", "{{TOKEN_NAME}}", "true") #Generate token and save in a variable
send_test_email(smtp_api_token) #Send email using the token we just generated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment