6

I am trying to send a simple mail with python

import smtplib

server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("[email protected]", "mypassword")

msg = "Hello world"
server.sendmail("[email protected]", "[email protected]", msg)
server.quit()

But I get this err:

server.login("[email protected]", "psw")

File "C:\Python\lib\smtplib.py", line 652, in login

raise SMTPAuthenticationError(code, resp)

smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbuxb\n5.7.14 4i2u8qU8V3jgf6uGv8da1RAGPJyctRvIFy_kjai6aKVx_B6qVhoz_dzFpvfPC18H-jeM6K\n5.7.14 cnm2HVuq-wr-uw59hD31ms-cxMmnZuq6Z3_liDaDmu8_UqaiUwR4FUiuX2i5pPdQjJzFvv\n5.7.14 4VrEF5XT4ol2iN17gnB_jITpwzsjH9Ox3NCNcfl7SriHr5m7esc15PWI0CG_2CTlyh7RxW\n5.7.14 XhoJPajs8GMd-khOQWUqucywfrfo> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 ef10sm13614207wjd.49 - gsmtp')

What should I do?

Thanks

16
  • 2
    @Yura, I'm terribly sorry, but when I try to login into your main (using data shown in the error message) I'm asked to verify it's you. So, you have two-factor authorization. Again, I beg your pardon for doing this. You should definitely remove your login and password from here. Commented May 30, 2015 at 17:48
  • 1
    @Yura, that means, you should handle two-factor auth somehow. Either disable this either dig into some docs on it and use some API if Google provides any. Commented May 30, 2015 at 17:50
  • 1
    Their are lots of tutorials on the internet, quote the stack overflow guidelines, "show your own research". Commented May 30, 2015 at 17:52
  • 1
    You need to spend more time on your spelling, you can get banned for that. (It's not that hard!) Almost every sentence has a typo. Please edit your comments for spelling, for your sake (being banned), and our sake. Commented May 30, 2015 at 17:53
  • 1
    It says in the error where to go: support.google.com/mail/bin/answer.py?answer=78754 Commented May 30, 2015 at 17:57

4 Answers 4

7

It seems as if you require something that Google calls an app password.

Basically, you generate a 16 digit password, which is unique to your app. You enter this specific password in the python program, instead of the password you regularly use to log into your Google account.

This allows you to still enjoy the benefits of 2-step verification while also being able to use third party applications, such as your own python program.

Here are the instructions from Google on how to generate such an app password: https://support.google.com/accounts/answer/185833?hl=en

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the detailed explanation and answer. This has worked!
3

you can use this code:

import smtplib

session = smtplib.SMTP('smtp.gmail.com', 587)
session.ehlo()
session.starttls()
session.login('[email protected]',' password')
headers = "\r\n".join(["from: " + '[email protected]',
                       "subject: " + "test",
                       "to: " + '[email protected]',
                       "mime-version: 1.0",
                       "content-type: text/html"])

# body_of_email can be plaintext or html!                    
content = headers + "\r\n\r\n" + "body_of_email"
session.sendmail('[email protected]', '[email protected]', content)

just remember if your email is gmail after first run you get an error. after that you should login to your email account and approve access to your account from another app ( you will receive a messege after login)

1 Comment

@SaraSantana Please have a look at yagmail, it should make it very easy to send emails!
2

You could use a free mail API such as mailgun:

import requests

def send_simple_message(target):
    return requests.post(
        "https://api.mailgun.net/v3/samples.mailgun.org/messages",
        auth=("api", "key-3ax6xnjp29jd6fds4gc373sgvjxteol0"),
        data={"from": "Excited User <[email protected]>",
              "to": [target],
              "subject": "Hello",
              "text": "Testing some Mailgun awesomeness!"})

send_simple_message('[email protected]')

Using an API like this avoids the issue of individual account authentication all together.

See also: This question for info on using smtplib

1 Comment

@Yura. Yup. I still think adding alternate solutions improves that quality of a question for future readers. Glad you got your answer!
1

Yea, like the answer posted, it was a matter of authentication :)

I'd like to further help you with sending emails by advising the yagmail package (I'm the maintainer, sorry for the advertising, but I feel it can really help!). Note that I'm also maintaining a list of common errors there, such as the authentication error.

The whole code for you would be:

import yagmail
yag = yagmail.SMTP('user', 'pw')
yag.send(contents = msg)

Note that I provide defaults for all arguments, for example if you want to send to yourself, you can omit "to = [email protected]", if you don't want a subject, you can omit it also.

Furthermore, the goal is also to make it really easy to attach html code or images (and other files).

Where you put contents you can do something like:

contents = ['Body text, and here is an embedded image:', 'http://somedomain/image.png',
            'You can also find an audio file attached.', '/local/path/song.mp3']

Wow, how easy it is to send attachments! This would take like 20 lines without yagmail ;)

Also, if you set it up once, you'll never have to enter the password again (and have it safely stored). In your case you can do something like:

import yagmail
yagmail.SMTP().send(contents = contents)

which is much more concise!

I'd invite you to have a look at the github or install it directly with pip install yagmail.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.