2016-10-01 161 views
2

我想要做的是讓我的Python代碼發送電子郵件。此代碼應該使用雅虎smtp發送電子郵件。我不需要任何附件或其他任何東西。代碼錯誤地說Error: unable to send email.除了顯示正確的電子郵件接收者和發件人地址之外,我該怎麼做才能讓這件事情起作用?發送電子郵件與Python腳本

#!/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 = ['[email protected]'] 
EMAIL_SENDER = '[email protected]' 
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) 
+1

請在提問之前閱讀幫助中心。這個問題沒有清楚地說明問題所在。在發帖前閱讀文章「如何提出問題」 – techydesigner

+0

此外,默認電子郵件地址仍然存在 – techydesigner

+0

我知道默認電子郵件地址仍然存在。我在帖子中說過。當我更改默認地址時,它仍然不起作用。 – ineedhelp

回答

1

我不知道雅虎,但谷歌通過他們的smtp端口阻止登錄。 否則就太容易進行暴力攻擊了。所以,即使您的代碼完全正常,登錄仍然可能因此而失敗。我試圖爲我的Gmail帳戶做同樣的事情。