Categories
Python Answers

How to send an email with Gmail as provider using Python?

Spread the love

Sometimes, we want to send an email with Gmail as provider using Python.

In this article, we’ll look at how to send an email with Gmail as provider using Python.

How to send an email with Gmail as provider using Python?

To send an email with Gmail as provider using Python, we can use smtplib.

For instance, we write

def send_email(user, pwd, recipient, subject, body):
    import smtplib

    FROM = user
    TO = recipient if isinstance(recipient, list) else [recipient]
    SUBJECT = subject
    TEXT = body

    message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(user, pwd)
        server.sendmail(FROM, TO, message)
        server.close()
        print('successfully sent the mail')
    except:
        print("failed to send mail")

to create the message message by putting the FROM, TO , SUBJECT and TEXT into the string.

Then we call smptlib.SMTP to connect to the server.

And then we call login to log in.

We call sendmail to send the message.

And then we call close to close the connection.

Conclusion

To send an email with Gmail as provider using Python, we can use smtplib.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to send an email with Gmail as provider using Python?”

Sorry but now, since may 30 2022, you must connect to google stmp with oauth2 🙁

this code give us “smtplib.SMTPAuthenticationError: (535, b’5.7.8 Username and Password not accepted. … ‘)

Leave a Reply

Your email address will not be published. Required fields are marked *