12 Days of DigitalOcean (Day 12) - Sending Confirmation Emails with Resend

Jan 08, 2025 11:30 PM - 1 week ago 12419

Welcome to the last time of our 12 Days of DigitalOcean series! We’ve travel a agelong way, building an Email-Based Receipt Processing Service that extracts receipt specifications from https://www.digitalocean.com/community/tutorials/setting-up-postmark-for-receipts utilizing DigitalOcean’s GenAI Agent, securely stores attachments successful DigitalOcean Spaces, and saves the extracted information successful Google Sheets.

Today, we’ll adhd the last touch—sending confirmation emails backmost to the sender pinch the receipt details, attachment links, and a nexus to the Google Spreadsheet. This last measurement ties everything together, ensuring that users get contiguous feedback that their receipts person been successfully processed.

🚀 What You’ll Learn

By the extremity of this tutorial, you’ll cognize really to:

  1. Use the Resend API to nonstop confirmation emails programmatically.
  2. Securely negociate delicate credentials utilizing situation variables.
  3. Format and nonstop transactional emails pinch receipt details, attachment links, and spreadsheet URLs.
  4. Test and troubleshoot a complete email processing workflow.

🛠 What You’ll Need

If you’d for illustration to build along, we presume that you’ve followed Day 11: Save Receipt Data and Attachments successful Google Sheets and already have:

  • A deployed Flask app for processing receipt emails.
  • Google Sheets and DigitalOcean Spaces integration group up.

If you’re conscionable willing successful learning really to merge Resend for sending confirmation emails, you’ll need:

  • A Resend account: Sign up astatine Resend.
  • An API key: Generate it from your Resend dashboard.

Step 1: Create a Resend Account and Get the API Key

To nonstop emails programmatically, we’ll usage Resend, a developer-friendly API for sending transactional emails. It simplifies sending emails truthful you don’t person to wrestle pinch mounting up an email server, managing SMTP configurations, aliases worrying astir spam filters.

  1. First, spell to Resend and motion up for a free account. Once logged in, navigate to the API Keys conception of the dashboard and make a caller API key.

    API Keys Dashboard Screenshot

  2. Give your API cardinal a descriptive name, for illustration Receipt Processor App, and group its permission to Full Access.

    Add API Key Receipt Processor

  3. Copy the API Key: Your API cardinal will beryllium shown only once—copy it and support it safe. You’ll request it successful the adjacent measurement to authenticate your app pinch Resend.

    View Resend API Key Warning

Step 2: Update Your Environment Variables

Now that we person the Resend API key, let’s prevention it arsenic an situation adaptable successful DigitalOcean, conscionable for illustration we’ve been doing passim this series.

For the Resend integration, we request to prevention 2 situation variables:

  • RESEND_API_KEY: The API cardinal you generated successful Step 1, which authenticates your app pinch Resend.
  • RESEND_EMAIL_FROM: The sender email reside you’ll usage to nonstop confirmation emails. This should beryllium an reside verified successful your Resend account.

To adhd these variables, travel these steps:

  1. Head complete to your DigitalOcean App Platform dashboard, find your Flask app, and navigate to the Settings tab. Under Environment Variables, adhd the 2 variables:

    • Key: RESEND_API_KEY

      • Value: Paste the API cardinal you generated successful Step 1.
    • Key: RESEND_EMAIL_FROM

      • Value: Enter a verified sender email reside from your Resend account.
  2. Save your changes to make the Resend API cardinal disposable to your Flask app, which we will update next.

    DigitalOcean Project Settings

Step 3: Install the Resend Python Library

Next, we’ll instal the Resend Python room to grip the API for us. It keeps your codification cleanable and avoids dealing pinch earthy HTTP requests. Run this successful your terminal:

pip install resend

Step 4: Update requirements.txt

Instead of editing requirements.txt by hand, usage pip frost to database each installed limitations pinch nonstop versions. Run this:

pip frost > requirements.txt

This updates requirements.txt pinch everything your app needs, including resend.

Step 5: Write the Function to Send Emails

Now it’s clip to adhd the logic for sending confirmation emails. Think of it for illustration emailing a friend to fto them cognize their package has arrived—only here, it’s for receipts.

We’ll constitute a send_confirmation_email usability that takes the recipient’s email, receipt details, attachment links, and Google Spreadsheet URL. Using Resend, it will format this into an email and nonstop it. Here’s the function:

def send_confirmation_email(to_email, receipt_data, attachment_urls, spreadsheet_url): """ Send a confirmation email pinch receipt specifications and attachment URLs. """ email_from = os.getenv('RESEND_EMAIL_FROM') taxable = "Receipt Processed Successfully" email_body = f""" <h1>Receipt Confirmation</h1> <p>Your receipt has been successfully processed. Here are the details:</p> <ul> <li><strong>Vendor:</strong> {receipt_data.get('vendor', 'N/A')}</li> <li><strong>Amount:</strong> {receipt_data.get('amount', 'N/A')}</li> <li><strong>Currency:</strong> {receipt_data.get('currency', 'N/A')}</li> <li><strong>Date:</strong> {receipt_data.get('date', 'N/A')}</li> </ul> <p><strong>Attachments:</strong></p> <ul> {''.join(f'<li><a href="{url["url"]}">{url["file_name"]}</a></li>' for url in attachment_urls)} </ul> <p>You tin position the processed information successful the spreadsheet: <a href="{spreadsheet_url}">Google Spreadsheet</a></p> """ try: resend.Emails.send({ "from": email_from, "to": to_email, "subject": subject, "html": email_body }) logging.info(f"Confirmation email sent to {to_email}.") except Exception as e: logging.error(f"Failed to nonstop confirmation email: {e}")

Step 5: Deploy to DigitalOcean

To deploy the updated Flask app, travel the steps from Day 7: Building and Deploying the Email-Based Receipt Processor. Here’s a speedy summary:

  1. Push Your Updated Code to GitHub: After making the basal changes to your Flask app, perpetrate and push the updated codification to GitHub. This will trigger an automatic deployment successful DigitalOcean’s App Platform.

    git add . git perpetrate -m "Add Resend integration for confirmation emails" git push root main
  2. Monitor Deployment: You tin way the advancement successful the Deployments conception of your app’s dashboard.

    DigitalOcean task dashboard showing deployment status

  3. Verify Your Deployment: After the deployment completes, navigate to your app’s nationalist URL and trial its functionality. You tin besides cheque the runtime logs successful the dashboard to corroborate that the app started successfully.

    DigitalOcean app deployment position and configuration

  4. Check Runtime Logs: If thing isn’t moving arsenic expected, usage the Runtime Logs tab successful the App Platform dashboard to debug runtime issues. Look for immoderate errors related to the Resend API aliases different app components.

Step 5: Test the Entire Workflow

Now that your app is afloat configured and ready, it’s clip to trial the full workflow. We’ll guarantee that the email assemblage is processed, attachments are decoded and uploaded to DigitalOcean Spaces, receipt specifications and attachment URLs are saved successful Google Sheets, and a confirmation email is sent to the sender.

Here’s really you tin trial measurement by step:

  1. Send a Test Email: Send an email to Postmark pinch a matter assemblage and an attachment. If you’re unsure really to configure Postmark, cheque Day 8: Connecting Postmark to Your Flask App, wherever we walked done mounting up Postmark to guardant emails to your app.

    Example of an email invoice receipt pinch highlighted costs specifications and attachments

  2. Check Postmark Activity JSON: In the Postmark dashboard, navigate to the Activity tab. Locate the email you sent and guarantee that the JSON payload includes the matter assemblage and Base64-encoded attachment data. This confirms Postmark is correctly forwarding the email information to your app, arsenic we group up successful Day 8.

    Postmark JSON consequence showing encoded email attachments pinch metadata

  3. Monitor the Logs: Check the runtime logs successful your DigitalOcean App Platform dashboard to guarantee the app processes the JSON payload. You should spot logs showing that receipt specifications were extracted and attachments were uploaded to DigitalOcean Spaces. You tin entree the runtime logs successful the Logs tab of the DigitalOcean App Platform dashboard. If you’re not acquainted pinch DigitalOcean logs, we explored this during Day 9: Automating Receipt Parsing withDigitalOcean’s GenAI Agent.

    DigitalOcean runtime logs interface displaying exertion log entries

  4. Verify Spaces Upload: Visit your DigitalOcean Space to corroborate that the files were uploaded successfully. You should spot the attachments successful your bucket arsenic configured successful Day 10: Storing Attachments successful DigitalOcean Spaces. If everything went arsenic expected, your attachment URLs will beryllium accessible.

    DigitalOcean Spaces interface showing uploaded files pinch names and metadata

  5. Check Google Sheets: Open your Google Sheet and corroborate that a caller statement pinch receipt specifications and attachment URLs has been added, arsenic we group up connected Day 11: Saving Receipt Details successful Google Sheets. The statement should include:

    • Vendor, amount, currency, and day extracted from the email body.
    • Comma-separated URLs for the uploaded attachments successful the past column.

    Google Sheets Receipts

  6. Verify the Confirmation Email: Finally, cheque the inbox of the sender’s email reside to guarantee the confirmation email was received. This email should contain:

    • The extracted receipt specifications (vendor, amount, currency, and date).
    • Links to the uploaded attachments successful DigitalOcean Spaces.
    • A nexus to the Google Spreadsheet wherever the receipt information is logged.

    Receipt Confirmation Email

Troubleshooting

If the workflow doesn’t activity arsenic expected, present are a fewer troubleshooting steps to follow:

  1. Check the Resend Emails Dashboard for Errors: Visit the Resend dashboard to spot if immoderate errors occurred while sending the confirmation email.

  2. Verify Environment Variables: Make judge the API cardinal (RESEND_API_KEY) and sender email (RESEND_EMAIL_FROM) are correctly configured successful your situation variables connected the DigitalOcean App Platform dashboard.

  3. Inspect DigitalOcean Runtime Logs: Open the Runtime Logs tab successful your DigitalOcean App Platform dashboard to cheque for errors while processing the email aliases uploading attachments. These logs tin supply adjuvant insights, particularly for interactions pinch Postmark aliases Resend.

  4. Review Postmark Activity: In Postmark’s Activity tab, corroborate that the trial email was decently forwarded to your Flask app. If location are immoderate issues, Postmark will show errors related to forwarding aliases configuration problems.

🎁 Wrap-Up

Congratulations! You’ve successfully completed the 12 Days of DigitalOcean bid and built a afloat functional Email-Based Receipt Processing Service.

Today, you:

  • Integrated the Resend API for sending transactional emails.
  • Configured situation variables to securely negociate delicate credentials.
  • Sent confirmation emails pinch receipt details, attachment links, and a spreadsheet URL.
  • Tested the afloat workflow from email submission to last confirmation.

By adding confirmation emails, you’ve wrapped up a task that processes emails, extracts details, stores attachments, and keeps everything organized successful Google Sheets. It’s user-friendly, practical, and fresh to lick real-world problems.

📚 The 12 Days of DigitalOcean

This marks the extremity of the 12 Days of DigitalOcean series. Over the past 12 days, we’ve built 2 real-world applications, 1 measurement astatine a time. Along the way, you’ve utilized devices for illustration DigitalOcean’s Serverless Functions, App Platform, Spaces Object Storage, PostgreSQL, DigitalOcean GenAI, Twilio, Google Sheets API, Postmark, PaperTrail, and Resend. Each portion came together to shape thing greater than the sum of its parts.

Here’s a speedy recap of what you’ve built:

🎂 Days 1–6: Build a Birthday Reminder Service

This app tracks birthdays and sends SMS reminders automatically. It’s lightweight, serverless, and easy to maintain.

  • Day 1: Set Up a PostgreSQL Database
    Create a database to shop interaction details.
  • Day 2: Connect to PostgreSQL pinch Python
    Securely link to your database and fetch data.
  • Day 3: Check Birthdays and Send SMS Notifications
    Use Twilio to notify users astir upcoming birthdays.
  • Day 4: Deploy to DigitalOcean Functions
    Deploy your app to the unreality pinch DigitalOcean Functions.
  • Day 5: Automate Daily Reminders pinch Triggers
    Schedule reminders to tally each time automatically.
  • Day 6: Set Up External Logging
    Monitor and troubleshoot your app pinch Papertrail.

By Day 6, you person a afloat automated work moving successful the cloud. It conscionable works.

📧 Days 7–12: Build an Email Receipt Processor

This app handles emailed receipts, extracts the needed details, and organizes everything successful a database.

  • Day 7: Build and Deploy a Flask App
    Set up a lightweight app to process receipt emails.
  • Day 8: Integrate Postmark for Email Processing
    Forward emails to your app for processing.
  • Day 9: Extract and Clean Data pinch DigitalOcean’s GenAI
    Use GenAI to extract system information from email content.
  • Day 10: Configure DigitalOcean Spaces for Secure Storage
    Store email attachments securely pinch entity storage.
  • Day 11: Save Receipt Data to Google Sheets
    Organize system information successful a spreadsheet for easy access.
  • Day 12: Send Confirmation Emails Notify users astir successfully processed receipts.

By Day 12, you’ve built a complete instrumentality that handles receipts end-to-end.

What You’ve Learned

  1. Storing and Managing Data: You utilized PostgreSQL for system information retention and Google Sheets for easy, sharable information logging.
  2. Automating Workflows: With DigitalOcean Functions and scheduling triggers, you automated processes and made your apps tally for illustration clockwork.
  3. Adding Intelligence to Your Apps: By integrating DigitalOcean’s GenAI, you brought intelligent information extraction and statement into your workflows, making your apps smarter and much capable.
  4. Handling Files Securely: You worked pinch DigitalOcean Spaces to shop and negociate files successful a reliable, scalable way.
  5. Enhancing Apps pinch APIs: APIs for illustration Twilio, Postmark, and Resend brought functionality for illustration SMS notifications, email forwarding, and confirmation emails to your apps.
  6. Debugging and Monitoring: Using devices for illustration Papertrail, you learned to debug and monitor your apps effectively, keeping them moving smoothly.

What’s next

This is conscionable the beginning—what you’ve learned present tin beryllium applied to countless different projects. Here are a fewer ways to support going:

  • Join the speech connected DigitalOcean’s Discord to link pinch different developers, stock what you’ve built, and get inspired.
  • Explore much successful our tutorial library for much ideas and projects.

If you travel along, I’d emotion to spot what you create—feel free to stock your advancement aliases feedback pinch maine connected Twitter.

Keep it simple. Build thing useful. Happy building! 🚀

More