How to extract text content from HTML in mailgun email function

I’m working with a mailgun email function and I have both text and HTML versions of my message. I want to get the text value and use it inside the HTML content somehow.

def dispatch_email_message():
    return requests.post(
         "https://api.mailgun.net/v3/DOMAIN/messages",
         auth=("api", "API_TOKEN"),
         files=[("attachment", ("image.png", open("uploads/image.png","rb").read())),
                ("attachment", ("document.pdf", open("uploads/document.pdf","rb").read()))],
         data={"from": "Support Team <[email protected]>",
             "to": "[email protected]",
             "cc": "[email protected]",
             "bcc": "[email protected]",
             "subject": "Welcome Message",
             "text": "Welcome to our platform!",
             "html": "<html><body>HTML email content here</body></html>"})

Is there a method to access the text field value and incorporate it into the HTML field? Any suggestions would be helpful.

You’re overthinking this. Those text and HTML fields are just parameters for the API call. If you need to pull text from HTML, use BeautifulSoup - from bs4 import BeautifulSoup, then soup = BeautifulSoup(html_content, 'html.parser') and text_content = soup.get_text(). But honestly? Define your content upfront instead of extracting it backwards. Email systems want both versions since plain text is the fallback when HTML fails.

just store your text in a var first. like msg_text = "Welcome to our platform!" then use it in both "text": msg_text and "html": f"<html><body>{msg_text}</body></html>". way simpler than extracting it later.

I’ve handled this before and a template function works great. Define your base message once, then format it for both text and HTML versions. Here’s what I use:

def get_message_content():
base_text = “Welcome to our platform!”
return {
“text”: base_text,
“html”: f"

{base_text}

Additional HTML formatting here

"
}

content = get_message_content()
data = {
“text”: content[“text”],
“html”: content[“html”]
}

Keeps both versions in sync and your code clean. No extraction headaches later.