简体   繁体   中英

How to send an email through gmail using python?

I'm trying to send emails with my gmail account using python. I've already read many questions here and around the Internet, but none of them solved my problem.

The code that I'm using is the following (thanks to rosettacode ), which is very similar to many other code snippets that can be found about this topic:

def sendemail(from_addr, to_addr_list, cc_addr_list,
              subject, message,
              login, password,
              smtpserver='smtp.gmail.com:587'):
    header  = 'From: %s\n' % from_addr
    header += 'To: %s\n' % ','.join(to_addr_list)
    header += 'Cc: %s\n' % ','.join(cc_addr_list)
    header += 'Subject: %s\n\n' % subject
    message = header + message

    server = smtplib.SMTP(smtpserver)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(login,password)
    problems = server.sendmail(from_addr, to_addr_list, message)
    server.quit()
    return problems

My problem is during the login phase. It returns the following error message:

SMTPAuthenticationError: (534, '5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbsMX\n5.7.14 Z4_8qLgwTbhS2CwFvVApFvRfpIS1Vbbfun6gHcf0D6jgSQ-ixMn79mf3AivveTs9IhYsgq\n5.7.14 pmrp157H4Vmk6-ybAC9u2d2lNMYyy5pdmociqeSxBBwFGEPGJKHKdJpSocx86gzG-im6V-\n5.7.14 hsOeMKiJRAuGZjHUprEwj8oABwLzWQ8vEzovpXk79M-i8cnFseW-PNLxLlsK21WaLHLKmZ\n5.7.14 Ll3tEgQ> Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 dc8sm25406976wib.7 - gsmtp')

I followed the suggested link and I found this answer , but I don't know if it could be the solution.

So, what's the problem? My account's settings? My code?

Google has recently tightened their security. Application that use username/password directly have been deactivated. All users are still able to reactivate these less secure application in their security settings as you have been reading in the link you gave in your question. This is the only solution at this point.

The alternative would be to use an other SMTP server for sending.

The error message you quote says

[..] Please log in via your web browser and then try again.
5.7.14 Learn more at
5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754

This was already discussed in server send emails using gmail smtp gets alerts .

So I'd say that your code is fine and you're dealing with a Google-specific security mechanism.

You could enable Google's 2-step authentication and then generate an application-specific password for your script. I do the same (I also have similar code as you) and it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM