Skip to main content
 首页 » 编程设计

python之使用 gmail smtp 从我的 python 脚本发送报告

2025年05月04日16mate10pro

我正在尝试向自己发送电子邮件,其中包含每天从我的脚本中收集的所有报告,下面是我用来发送电子邮件的代码。

# Import smtplib for the actual sending function 
import smtplib 
 
# Import the email modules we'll need 
from email.mime.text import MIMEText 
 
def send_email(message="", subject="EReport of Twitter Bot"): 
    msg = MIMEText(message) 
 
    # me == the sender's email address 
    # you == the recipient's email address 
    msg['Subject'] = subject 
    msg['From'] = 'r****@gmail.com' 
    msg['To'] = 'r****@gmail.com' 
 
    # Send the message via our own SMTP server, but don't include the 
    # envelope header. 
    try: 
        s = smtplib.SMTP('smtp.gmail.com',465) 
        s.ehlo() 
        s.starttls() 
        s.ehlo() 
        s.login('r****@gmail.com', 'mypassword') 
        s.sendmail('r****@gmail.com', 'r****@gmail.com', msg.as_string()) 
        s.quit() 
        return True 
    except Exception as e: 
        print e 
        return False 
 
if __name__ == "__main__": 
    if send_email(message="Hello Ravi!"): 
        print "Successfully sent the mail" 
    else: 
        print "Sorry" 

但是,在使用端口 465 时,我得到连接意外关闭。如果我使用端口 587,我得到以下信息

(534, '5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvkf\n5.7.14 g4kEFJrti_fMva0wSRWGl4KfuNsFhQumLhgzMCUlPCQn2dvYdPCDr03l9luBP2XTwcnf_N\n5.7.14 BNsPV2jZhLOPjFOSYtGM16Wb6A1BlmLvMP1_mMHoeo4plSVNGio8EDCx_RMW7HcJdYcpx9\n5.7.14 T5SHwceKzRdpUXHxdL2icc0KAMDtb1dDLDr389N_s-tnSkylcN0bwctBA0tKF2k0AC6OsX\n5.7.14 jIcP7iV3ArV6PEB2ZXPCOI2gRPg0> 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/answer/78754 lq10sm97657764pab.36 - smtp') 

这基本上意味着我的服务器不值得信任,尽管我服务器 ip 上的反向 dns 返回有效的 rent-history.com

有谁知道我可以做什么/尝试解决这个问题?

请您参考如下方法:

端口 465 用于 SSL,端口 587 不使用。

当您打算使用安全连接(端口 465)和带有端口 587 的 SMTP 时,您应该使用 SMTP_SSL。

另外,我想指出 yagmail ;我开发了它。

你可以只使用:

import yagmail 
yag = yagmail.SMTP('r****@gmail.com', 'pw') # or yagmail.SMTP_SSL for port 465 
yag.send('r****@gmail.com', "EReport of Twitter Bot", message) 

此外,它还可以轻松地:

  • 以无密码方式编写脚本
  • 按文件名添加文件(它会自动使用正确的 mime 类型附加文件)
  • 它会自动发送 HTML 电子邮件并使用纯文本回退

使用 pip 安装(适用于 python 2 和 3):

pip install yagmail