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("mymail@gmail.com", "mypassword")

msg = "Hello world"
server.sendmail("mymail@gmail.com", "mymail@gmail.com", msg)
server.quit()

But I get this err:

server.login("user@gmail.com", "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

Yura
  • 2,381
  • 8
  • 33
  • 44
  • Have you tried logging in using your browser and trying again as the error message says? Have you tested the scheme of logging in in your terminal? – ForceBru May 30 '15 at 17:40
  • is your gmail account have active 2 step verification??? – Hackaholic May 30 '15 at 17:40
  • @ForceBru, Yes, I have tried logging in via browser and while I am logged in to try this - it does not work. I also tried the same lines via terminal and also can no do it.. – Yura May 30 '15 at 17:45
  • @Hackaholic, when I log in to my gmail, I only enter my usernam and pswd. Thats all. – Yura May 30 '15 at 17:46
  • 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. – ForceBru May 30 '15 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. – ForceBru May 30 '15 at 17:50
  • @ ForceBru, ooops. Thanks for wanrning me. Removed. So what should I do with the 2-step authintication? How can I send mail while using it? What should I do with it? – Yura May 30 '15 at 17:51
  • 1
    Their are lots of tutorials on the internet, quote the stack overflow guidelines, "show your own research". – noɥʇʎԀʎzɐɹƆ May 30 '15 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. – noɥʇʎԀʎzɐɹƆ May 30 '15 at 17:53
  • 1
    It says in the error where to go: https://support.google.com/mail/bin/answer.py?answer=78754 – Alexander May 30 '15 at 17:57
  • 1
    @Yura You can use something called an [application password.](https://support.google.com/accounts/answer/185833?hl=en) to authenticate the python program. – Wilhelm Klopp May 30 '15 at 18:05
  • @ CrazyPython, thanks for paying my attention to my typos, I'll be more careful :) by the way, I did spend time on trying to find answers, it is just that all the code was the same as mine and I couldn't understand why mine wasn't working... – Yura May 30 '15 at 18:05
  • @ ForceBru, thanks. I dont mind if they can be seen. I have regenerated my psw :) – Yura May 30 '15 at 18:08
  • 1
    [sendgrid](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) offers an API to send emails via POST requests. That might be an easy alternative. – Martin Thoma May 30 '15 at 18:14
  • Thank you all for your help and support! – Yura May 30 '15 at 18:34
  • Guys, please have a look at [yagmail](https://github.com/kootenpv/yagmail)! It's really difficult to get a new package for sending emails noticed, but I really feel like it can help everyone out! See my answer below for a small demonstration. – PascalVKooten May 31 '15 at 09:21

4 Answers4

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

Wilhelm Klopp
  • 5,030
  • 2
  • 29
  • 37
3

you can use this code:

import smtplib

session = smtplib.SMTP('smtp.gmail.com', 587)
session.ehlo()
session.starttls()
session.login('youremail@gmail.com',' password')
headers = "\r\n".join(["from: " + 'youremail@gmail.com',
                       "subject: " + "test",
                       "to: " + 'contactemail@gmail.com',
                       "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('youremail@gmail.com', 'contactemail@gmail.com', 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)

Sara Santana
  • 1,001
  • 1
  • 11
  • 22
  • @SaraSantana Please have a look at [yagmail](https://github.com/kootenpv/yagmail), it should make it very easy to send emails! – PascalVKooten May 31 '15 at 09:22
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 <excited@samples.mailgun.org>",
              "to": [target],
              "subject": "Hello",
              "text": "Testing some Mailgun awesomeness!"})

send_simple_message('target@email.com')

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

See also: This question for info on using smtplib

Community
  • 1
  • 1
David Greydanus
  • 2,551
  • 1
  • 23
  • 42
  • @Yura. Yup. I still think adding alternate solutions improves that quality of a question for future readers. Glad you got your answer! – David Greydanus May 30 '15 at 18:49
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 = myemail@gmail.com", 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.

PascalVKooten
  • 20,643
  • 17
  • 103
  • 160