简体   繁体   中英

Python sending email via Gmail failed

I am using this piece of code:

import smtplib

fromaddr = 'fromuser@gmail.com'
toaddrs  = 'myemail@gmail.com'
msg = 'There was a terrible error that occured and I wanted you to know!'


# Credentials (if needed)
username = 'myusername'
password = 'passwd'

# The actual mail send
server = smtplib.SMTP_SSL('smtp.gmail.com',465)
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

I am receiving this error:

Traceback (most recent call last): File "C:/Python34/sendemail.py", line 15, in server.starttls() File "C:\\Python34\\lib\\smtplib.py", line 673, in starttls raise SMTPException("STARTTLS extension not supported by server.") smtplib.SMTPException: STARTTLS extension not supported by server.

When I do exculde server.starttls() I am receiving different error message about authentication. I have another price of code when I am accessing Gmail via web browser using webdriver and credentials works, so I copied and pasted to this code to make sure that credentials are correct.

I can't figure out why this is not working.

Thanks in advance.

you'll have to see here as well

use port 587

server=smtplib.SMTP('smtp.gmail.com',587)
server.starttls()

Sending via Gmail works for me when using this code. Note that I use smtplib.SMTP() as opposed to smtplib.SMTP_SSL('smtp.gmail.com',465) . Also try to use port 587 and not 465.

server = smtplib.SMTP()
server.connect(server, port)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(send_from, send_to, msg)
server.close()

Though I do find that using the emails library is much easier.

Please, try yagmail . Disclaimer: I'm the maintainer, but I feel like it can help everyone out!

It really provides a lot of defaults: I'm quite sure you'll be able to send an email directly with:

import yagmail
yag = yagmail.SMTP(username, password)
yag.send(to_addrs, contents = msg)

You'll have to install yagmail first with either:

pip install yagmail  # python 2
pip3 install yagmail # python 3

Once you will want to also embed html/images or add attachments, you'll really love the package!

It will also make it a lot safer by preventing you from having to have your password in the code.

你要么使用smtplib.SMTP()然后使用starttls()(我不推荐),要么单独使用smtplib.SMTP_SSL()(之后不要使用starttls())

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