Search code examples
gmailsmtplib

sending email from python 3.4 script, WITHOUT enabling 'less secure apps' in gmail


I would like to send mail using a python 3.4 script, from my gmail address. I use the following code:

import smtplib  

def sendmail():  
    sender='[email protected]'  
    receiver=['[email protected]']  
    message='text here'  
    try:  
        session=smtplib.SMTP('smtp.gmail.com',587)  
        session.ehlo()  
        session.starttls()  
        session.ehlo()  
        session.login(sender,'mypassword')  
        session.sendmail(sender,receiver,message)  
        session.quit()  
    except smtplib.SMTPException:  
        print('Error, can not send mail!')

If I 'allow less secure apps' in my gmail account, the script works fine. However, if I disable 'less secure apps', it doesn't work (I get a warning email from google, with 'sign-in attempt blocked') . I would like to modify my code, to be able to send mail without enabling this thing.

I have read all the questions and answers regarding similar problems, but did not find any useful answers or methods. Does someone have a solution for this?


Solution

  • From "Allowing less secure apps to access your account" support page

    Google may block sign in attempts from some apps or devices that do not use modern security standards.

    A login/password is not a modern mechanism to authenticate. You should implement SASL XOAuth2.