Weber Chang
Weber Chang

Reputation: 55

Efficiency of sending email in python

I am building a python program which can send emails in a certain time, below is my current code

def send_email(user):
    msg = email.message.EmailMessage()
    msg["From"] = "my Email"
    msg["To"] = user
    msg["Subject"] = "Subject"
    msg.add_alternative("content", subtype = "html")

    server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
    server.login("account", "password")
    server.send_message(msg)
    server.close()

I wanted to move the login process outside the send_email function so it doesn't have to login every time it needs to send emails, so I did this

server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.login("account", "password")

def send_email(user):
    msg = email.message.EmailMessage()
    msg["From"] = "my Email"
    msg["To"] = user
    msg["Subject"] = "Subject"
    msg.add_alternative("content", subtype = "html")

    server.send_message(msg)
    server.close()

But I started to get this error: smtplib.SMTPServerDisconnected: please run connect() first. How to solve this problem? Or is there any other way to improve the efficiency?

Upvotes: 2

Views: 117

Answers (1)

DeepSpace
DeepSpace

Reputation: 81604

You are calling server.close() every time you are calling send_email so it makes sense you'll need to connect/login again before being able to send another mail.

Move the server.close call to outside of the send_email function.

However, are you sure that keeping the session open is the best approach here? First I'd try to use a profiler to make sure the bottleneck is indeed in the login process and not somewhere else (ie the send process itself).

Upvotes: 2

Related Questions