无法通过python

时间:2018-08-29 14:01:25

标签: python gmail smtplib

我有一个工作半年前的代码。它基本上会发送电子邮件。

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)

这是个例外

  

(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>请通过

登录      

5.7.14您的网络浏览器,然后重试。

     

5.7.14了解更多信息

     

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

我确实尝试过

  • 登录的gmail
  • 将设备添加到受信任的设备
  • 通过gmail启用了IMAP
  • let less secure apps
  • 尝试了这个:

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

2 个答案:

答案 0 :(得分:0)

有很多方法可以解决此问题。我希望这段代码对您有所帮助。 您唯一需要做的就是填写所需的变量。

    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()

答案 1 :(得分:0)

我还建议使用一个更简单的库(在smtplib之上的包装器,以确保不涉及其他因素)....像yagmail(免责声明:我是开发人员)。

尝试看看是否可行:

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