Skip to main content
 首页 » 编程设计

python之使用 python 脚本发送电子邮件

2024年10月17日28cmt

我想要做的是让我的 python 代码发送电子邮件。此代码应该使用 yahoo smtp 发送电子邮件。我不需要任何附件或其他任何东西。代码在显示 错误:无法发送电子邮件的地方出错。 除了输入正确的电子邮件收件人和发件人地址之外,我还能做些什么才能使它正常工作?

#!/usr/bin/env python 
from smtplib import SMTP 
from smtplib import SMTP_SSL 
from smtplib import SMTPException 
from email.mime.text import MIMEText 
import sys 
 
#Global varialbes 
EMAIL_SUBJECT = "Email from Python script" 
EMAIL_RECEIVERS = ['receiverId@gmail.com'] 
EMAIL_SENDER  =  'senderId@yahoo.com' 
TEXT_SUBTYPE = "plain" 
 
YAHOO_SMTP = "smtp.mail.yahoo.com" 
YAHOO_SMTP_PORT = 465 
 
def listToStr(lst): 
    """This method makes comma separated list item string""" 
    return ','.join(lst) 
 
def send_email(content, pswd): 
    """This method sends an email""" 
    msg = MIMEText(content, TEXT_SUBTYPE) 
    msg["Subject"] = EMAIL_SUBJECT 
    msg["From"] = EMAIL_SENDER 
    msg["To"] = listToStr(EMAIL_RECEIVERS) 
 
    try: 
      #Yahoo allows SMTP connection over SSL.  
      smtpObj = SMTP_SSL(YAHOO_SMTP, YAHOO_SMTP_PORT) 
      #If SMTP_SSL is used then ehlo and starttls call are not required. 
      smtpObj.login(user=EMAIL_SENDER, password=pswd) 
      smtpObj.sendmail(EMAIL_SENDER, EMAIL_RECEIVERS, msg.as_string()) 
      smtpObj.quit(); 
    except SMTPException as error: 
      print "Error: unable to send email :  {err}".format(err=error) 
 
def main(pswd): 
    """This is a simple main() function which demonstrates sending of email using smtplib.""" 
    send_email("Test email was generated by Python using smtplib and email libraries", pswd); 
 
if __name__ == "__main__": 
    """If this script is executed as stand alone then call main() function.""" 
    if len(sys.argv) == 2: 
        main(sys.argv[1]) 
    else: 
        print "Please provide password" 
        sys.exit(0) 

请您参考如下方法:

我不知道雅虎,但谷歌阻止了通过他们的 smtp 端口登录。 否则进行蛮力攻击就太容易了。因此,即使您的代码完全正确,登录也可能因此而失败。我已尝试对我的 gmail 帐户执行完全相同的操作。