October 4, 2022

How to send emails with your Smart Forms

This Python-only lightning tutorial will show how to send emails from within your Smart Forms.

For that we’ll use SendGrid’s Python lib. To follow along, create a free SendGrid account and your single sender email API key.

This is the basic code you need to add to your Form’s script to send an email with a subject line, inner content and attachment:


# Import required libraries
from abstra.forms import *
import os
import base64
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition)

# Fill in email content
message = Mail(
    from_email= 'your_sender_email',
    to_emails= 'your_receiver_email',
    subject='Your email subject',
    html_content="""
        Add your customized content here.
        """)

# Add attachment, if needed
with open('your_attachment_file_name', 'rb') as f:
    data = f.read()
    f.close()
encoded_file = base64.b64encode(data).decode()

attachedFile = Attachment(
    FileContent(encoded_file),
    FileName('your_attachment_file_name'),
    FileType('application/vnd.openxmlformats-officedocument.wordprocessingml.document'),
    Disposition('attachment')
)
message.attachment = attachedFile
# End of attachment

# Send email
sg = SendGridAPIClient(os.environ.get('YOUR_SENDGRID_API_KEY'))
response = sg.send(message)

Infinite solutions can be customized from here on.

One example is using form answers + simple Python logic to populate the email’s content:


from abstra.forms import *
import os
import base64
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition)

name = read('What\'s your name?')
email = read_email('What\'s your email?')
seats = read_number('How many seats do you need?')

if seats < 5:
    plan = 'Starter'
    value = 50
elif 5 < seats < 20:
    plan = 'Pro'
    value = 100
elif seats > 20:
    plan = 'Enterprise'
    value = 300

message = Mail(
    from_email= 'your_sender_email',
    to_emails= email,
    subject='Estimated cost',
    html_content=f"""
        Hi there, {name}.
Thank you for your interest in our product!

Since you need {seats} seats, the recommended plan is the {plan} plan.
The price is ${value} per month.
Acess our landing page for more. """) sg = SendGridAPIClient(os.environ.get('YOUR_SENDGRID_API_KEY')) response = sg.send(message)

Check out 2 other example use cases (with interactive previews!):

Access Abstra to start creating your own projects.