0

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='myemail@gmail.com'  
    receiver=['someone@gmail.com']  
    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?

Sylvester Kruin
  • 3,294
  • 5
  • 16
  • 39
Wanek T
  • 25
  • 2
  • 6

1 Answers1

2

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.

rds
  • 26,253
  • 19
  • 107
  • 134
  • i see. this somewhat helped solving the problem. can somebody recommend a good tutorial for implementing oauth 2 in python? thanks! – Wanek T Apr 17 '15 at 20:40
  • See announcement http://googleappsdeveloper.blogspot.ch/2014/10/updates-on-authentication-for-gmail.html – rds Apr 18 '15 at 10:39
  • Never used it, but Gmail has released a library for XOAUTH2 https://code.google.com/p/google-mail-oauth2-tools/ – rds Apr 18 '15 at 10:42