简体   繁体   中英

Can't send email (gmail) via python

I have a code which was working like a half year ago. It basiclly sends email.

import smtplib
import socket

gmail_user="SENDERMAIL"
gmail_password="SENDERPASS"
to = 'SENDTOTHIS'

email_text = "ADSADSADSA"

try:
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_password)
    server.starttls()
    server.sendmail(gmail_user, to, email_text)
    server.close()

    #I was using this code below and it was working. I tried above code but it also did not work.
    #server = smtplib.SMTP("smtp.gmail.com:587")
    #server.ehlo()
    #server.starttls()
    #server.ehlo()
    #server.login(gmail_user, gmail_password)
    #server.sendmail(gmail_user, to, email_text)
    #server.close()
    print("Done")
except Exception as exception:
    print(exception)

Here's exception

(534, b'5.7.14

5.7.14 KL7_2qGSLW9IBjP8dKKgP67bEgyKNc5ls76dnVDZcUlVQjJUQb0JX9BIVi_Agb84vKNOKB

5.7.14 fshB0ngZ_Tn8ocDpDHKavRKXmluVjHo5YM7ADKENtWn4aVTxyvaBlbXRGpA1EBh91bdV-o

5.7.14 pwiAWUHXKmRQEuSNSiFcv68DP4a7ghIu9YKnTyqtUEhGd4HgKtxa4Jz0mhSQDjD13UQWYB

5.7.14 -YEL5Sd2h5YxN8kkSAsK-J_hXMbpy7wNyeCov8lq1Aa3spZzgo> Please log in via

5.7.14 your web browser and then try again.

5.7.14 Learn more at

5.7.14 https://support.google.com/mail/answer/78754 f132-v6sm3660398wme.24 - gsmtp')

I did try to

  • logined gmail
  • add device to trusted devices
  • turned on IMAP via gmail
  • let less secure apps
  • tried this:

https://support.google.com/mail/answer/7126229?visit_id=636711453029417344-336837064&rd=2#cantsignin

There are to many ways to solve this problem. I hope this code helps. The only thing you need to do is filling the required variables.

    import socket
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    # 
    message = "Your message" # Type your message
    msg = MIMEMultipart()
    password = "********" # Type your password 
    msg['From'] = "from@gmail.com" # Type your own gmail address 
    msg['To'] = "To@gmail.com" # Type your friend's mail address  
    msg['Subject'] = "title" # Type the subject of your message 
    msg.attach(MIMEText(message, 'plain'))
    server = smtplib.SMTP('smtp.gmail.com: 587')
    server.starttls()
    server.login(msg['From'], password)
    server.sendmail(msg['From'], msg['To'], msg.as_string())
    server.quit()

I can also advise to use a simpler library (a wrapper on top of smtplib, to make sure there are no other factors involved).... like yagmail (disclaimer: I'm the developer).

Try to see if this works:

import yagmail
yag = yagmail.SMTP("username", "password")
yag.send(subject="hi")

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