Menu Close

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

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.

Posted in Python, Python Answers