Contact Form - Sending Gmail Email and Receiving Gmail Email

Hello! I’m making a contact form, using a gmail email to send, and another to receive. And I get the error TypeError: ‘module’ object is not callable in the line def send_email(form_data: dict): Can someone help me?
import smtplib
import os

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from dotenv import load_dotenv

import reflex as rx

from rxconfig import config

from workaudit.template import template

Cargar las variables desde el archivo .env

load_dotenv()

def enviar():
“”“Función Enviar”“”
return rx.script

class FormSubmit(rx.State):
“”“Clase Formulario - -Enviar”“”
form_data: dict = {}
message: str = None

@rx.event
def send_email(form_data: dict):
“”“Enviar los datos del formulario por correo”“”

# Obtener datos del formularios
FormSubmit.form_data = form_data
FormSubmit.form_data["message"] = FormSubmit.message

# Información del correo (desde variable de entorno)
sender_email = os.getenv("SENDER_EMAIL")
receiver_email = os.getenv("RECEIVER_EMAIL")
password = os.getenv("EMAIL_PASSWORD")

# Crear mensaje:
subject = "Nuevo contacto desde el formulario"
body = f"""
Nombre: {FormSubmit.form_data['first_name']} {FormSubmit.form_data['last_name']}
Correo: {FormSubmit.form_data['email']}
Teléfono: {FormSubmit.form_data['phone']}
Mensaje: {FormSubmit.form_data['message']}
"""

msg = MIMEMultipart()
msg['from'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))

try:
    # Conectar al servidor STMP (gmail)
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, msg.as_string())

        print("correo enviado con éxito.")
        return rx.window_alert("correo enviado con éxito.")

except Exception as e:
    print(f"error al enviar el correo: {e}")
    return rx.window_alert("error al enviar el correo: {e}")

@rx.event
def set_message(value: str):
“”“Establecer mensaje”“”
FormSubmit.message = value

@rx.page(route=“/contact”)
@template
def contact_page() → rx.Component:
“”“Formulario de Contacto”“”
return rx.container(
rx.flex(
rx.heading(“Contacto”, size=“8”, color=“#000000”),
# rx.divider(size=“4”, width=“50px”, height=“5px”, border_radius=“5px”,
# background=“#000000”),
rx.spacer(),
rx.center(
rx.form(
rx.vstack(
rx.input(
placeholder=“Nombre”,
name=“first_name”,
is_required=True,
border_color=“#000000”,
focus_border_color=“#0000ff”,
background=“#ffffff”,
width=“100%”,
),
rx.input(
placeholder=“Apellido”,
name=“last_name”,
is_required=True,
border_color=“#000000”,
focus_border_color=“#0000ff”,
background=“#ffffff”,
width=“100%”,
),
rx.input(
placeholder=“Correo Electrónico”,
name=“email”,
is_required=True,
border_color=“#000000”,
focus_border_color=“#0000ff”,
type=“email”,
background=“#ffffff”,
width=“100%”,
),
rx.input(
placeholder=“Teléfono”,
name=“phone”,
is_required=True,
border_color=“#000000”,
focus_border_color=“#0000ff”,
type=“tel”,
background=“#ffffff”,
width=“100%”,
),
rx.text_area(
placeholder=“Escriba su mensaje aquí…”,
border_color=“#000000”,
focus_border_color=“#0000ff”,
min_height=“250px”,
is_required=True,
on_change=set_message,
background=“#ffffff”,
width=“100%”,
as_=“label”,
),
rx.center(rx.button(“Submit”, type=“submit”, color_scheme=“blue”, style={
“outline”: “none”}), width=“100%”),
),
on_submit=send_email,
reset_on_submit=True,
width=“95%”,
),
width=“80%”,
),
direction=“column”,
spacing=“5”,
justify=“center”,
align=“baseline”,
margin=“30px”,
),
padding=“80px 10px 10px 200px”,
width=“100%”,
background_color=“white”,
)

First thing first, could you format your code properly?
It will make it easier to read what you shared and then help you.

import smtplib
import os

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from dotenv import load_dotenv

import reflex as rx
# from rxconfig import config


from workaudit.template import template

# Cargar las variables desde el archivo .env
load_dotenv()


def enviar():
    """Función Enviar"""
    return rx.script


class FormSubmit(rx.State):
    """Clase Formulario - -Enviar"""
    form_data: dict = {}
    message: str = None


@rx.var
def send_email(form_data: dict):
    """Enviar los datos del formulario por correo"""

    # Obtener datos del formularios
    FormSubmit.form_data = form_data
    FormSubmit.form_data["message"] = FormSubmit.message

    # Información del correo (desde variable de entorno)
    sender_email = os.getenv("SENDER_EMAIL")
    receiver_email = os.getenv("RECEIVER_EMAIL")
    password = os.getenv("EMAIL_PASSWORD")

    # Crear mensaje:
    subject = "Nuevo contacto desde el formulario"
    body = f"""
    Nombre: {FormSubmit.form_data['first_name']} {FormSubmit.form_data['last_name']}
    Correo: {FormSubmit.form_data['email']}
    Teléfono: {FormSubmit.form_data['phone']}
    Mensaje: {FormSubmit.form_data['message']}
    """

    msg = MIMEMultipart()
    msg['from'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    try:
        # Conectar al servidor STMP (gmail)
        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
            server.login(sender_email, password)
            server.sendmail(sender_email, receiver_email, msg.as_string())

            print("correo enviado con éxito.")
            return rx.window_alert("correo enviado con éxito.")

    except Exception as e:
        print(f"error al enviar el correo: {e}")
        return rx.window_alert("error al enviar el correo: {e}")



def set_message(value: str):
    """Establecer mensaje"""
    FormSubmit.message = value


@rx.page(route="/contact")
@template
def contact_page() -> rx.Component:
    """Formulario de Contacto"""
    return rx.container(
        rx.flex(
            rx.heading("Contacto", size="8", color="#000000"),
            # rx.divider(size="4", width="50px", height="5px", border_radius="5px",
            # background="#000000"),
            rx.spacer(),
            rx.center(
                rx.form(
                    rx.vstack(
                        rx.input(
                            placeholder="Nombre",
                            name="first_name",
                            is_required=True,
                            border_color="#000000",
                            focus_border_color="#0000ff",
                            background="#ffffff",
                            width="100%",
                        ),
                        rx.input(
                            placeholder="Apellido",
                            name="last_name",
                            is_required=True,
                            border_color="#000000",
                            focus_border_color="#0000ff",
                            background="#ffffff",
                            width="100%",
                        ),
                        rx.input(
                            placeholder="Correo Electrónico",
                            name="email",
                            is_required=True,
                            border_color="#000000",
                            focus_border_color="#0000ff",
                            type="email",
                            background="#ffffff",
                            width="100%",
                        ),
                        rx.input(
                            placeholder="Teléfono",
                            name="phone",
                            is_required=True,
                            border_color="#000000",
                            focus_border_color="#0000ff",
                            type="tel",
                            background="#ffffff",
                            width="100%",
                        ),
                        rx.text_area(
                            placeholder="Escriba su mensaje aquí...",
                            border_color="#000000",
                            focus_border_color="#0000ff",
                            min_height="250px",
                            is_required=True,
                            on_change=set_message,
                            background="#ffffff",
                            width="100%",
                            as_="label",
                        ),
                        rx.center(rx.button("Submit", type="submit", color_scheme="blue", style={
                            "outline": "none"}), width="100%"),
                    ),
                    on_submit=send_email,
                    reset_on_submit=True,
                    width="95%",
                ),
                width="80%",
            ),
            direction="column",
            spacing="5",
            justify="center",
            align="baseline",
            margin="30px",
        ),
        padding="80px 10px 10px 200px",
        width="100%",
        background_color="white",
    )

I cannot tell if it is just formatted incorrectly but the send_email event needs to be inside your FormSubmit state and then needs to be referenced inside of the contact_page() function as on_submit=FormSubmit.send_email.

It would look something like this:

class FormSubmit(rx.State):
    """Clase Formulario - -Enviar"""
    form_data: dict = {}
    message: str = None

    @rx.var
    def send_email(self, form_data: dict):
    # Obtener datos del formularios
    self.form_data = form_data

Let me know if this helps.