Sending and reading email using python

286 Views Asked by At

I want to send and read emails using Python. For this purpose I used to use SMTP and IMAP. To connect using them I would enabled access to "Less secure app access" then login using username and password.

The problem is that today this option is no longer available.

I understood that there is some possibility to connect using the Google API, but it seems to me very complex and complicates the code. Until now the code was a few lines... If anyone has an idea how to connect to a Google account conveniently. Or at least an explanation of the Google API. I will thank him very much.

All the answers given in the forum on the issue of authentication problems for SMTP and IMAP are not relevant because of the cancellation of the option of "Less secure app access".

Thanks,

Jonathan

1

There are 1 best solutions below

2
Linda Lawton - DaImTo On BEST ANSWER

The easiest solution is to enable 2fa on the users google account, and create an apps password. Then just use the apps password in place of the users actual password in your code.

import smtplib
from email.mime.text import MIMEText


def send_email(host, port, subject, msg, sender, recipients, password):
    msg = MIMEText(msg)
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = ', '.join(recipients)
    smtp_server = smtplib.SMTP_SSL(host, port)
    smtp_server.login(sender, password)
    smtp_server.sendmail(sender, recipients, msg.as_string())
    smtp_server.quit()


def main():
    host = "smtp.gmail.com"
    port = 465

    user = "[redacted]@gmail.com"
    pwd = "shgrxehjiiniggpa"

    subject = "Test email"
    msg = "Hello world"
    sender = user
    recipients = [user]
    send_email(host, port, subject, msg, sender, recipients, pwd)


if __name__ == '__main__':
    main()

How I send emails with Python. In 2.2 minutes flat!