发送电子邮件与Python脚本
问题描述:
我想要做的是让我的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)
答
我不知道雅虎,但谷歌通过他们的smtp端口阻止登录。 否则就太容易进行暴力攻击了。所以,即使您的代码完全正常,登录仍然可能因此而失败。我试图为我的Gmail帐户做同样的事情。
请在提问之前阅读帮助中心。这个问题没有清楚地说明问题所在。在发帖前阅读文章“如何提出问题” – techydesigner
此外,默认电子邮件地址仍然存在 – techydesigner
我知道默认电子邮件地址仍然存在。我在帖子中说过。当我更改默认地址时,它仍然不起作用。 – ineedhelp