SMTP python sends two emails when i run it once

371 Views Asked by At

I have written a .py file to send a template email using jinja 2 and SMTP. The only issue I'm having is when I run the code once, the email sends twice (at the same time in the same email chain as an exact duplicate).

Here is the code I'm using:

from jinja2 import Environment, PackageLoader, select_autoescape

import smtplib
from email.message import EmailMessage
msg = EmailMessage()

content="hello"

def send_template_email(template, to, subj, **kwargs):
    env = Environment(
        loader=PackageLoader("send_template_email", "templates"),
        autoescape=select_autoescape(["html", "xml"])
    )
    template = env.get_template("email_template.html")
    send_email(to, subj, template.render(**kwargs))

def send_email(to, subj, body):
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login('[email protected]','password')
    msg['Subject'] = subj
    msg['From'] = "[email protected]"
    msg['To'] = to
    msg.set_content(body, subtype="html")
    server.send_message(msg)
    server.quit()

send_template_email(
    template="email_template.html",
    to="[email protected]",
    subj="TEST",
    content=content
)

in this example, [email protected] would receive 2 identical emails, but I only want them to receive one.

0

There are 0 best solutions below