简体   繁体   English

使用python脚本发送电子邮件

[英]Sending email with python script

What I'm trying to do is get my python code to send an email.我想要做的是让我的 python 代码发送电子邮件。 This code is supposed to use the yahoo smtp to send the email.此代码应该使用雅虎 smtp 发送电子邮件。 I don't need any attachments or anything else.我不需要任何附件或其他任何东西。 The code bugs out where it says Error: unable to send email.代码错误显示Error: unable to send email. Other than the obvious of putting in correct email receiver and sender addresses, what can I do to get this thing to work?除了输入正确的电子邮件接收者和发件人地址这一显而易见的方法外,我还能做些什么来使这件事发挥作用?

#!/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)

I don't know about Yahoo, but Google blocked the login via their smtp-port.我不知道雅虎,但谷歌通过他们的 smtp 端口阻止了登录。 It would be way too easy to conduct brute force attacks otherwise.否则,进行蛮力攻击就太容易了。 So even if your code is perfectly ok, the login might still fail because of that.因此,即使您的代码完全正确,登录也可能因此而失败。 I have tried to do the exact same thing for my gmail account.我试图为我的 gmail 帐户做同样的事情。

作为开发人员,我建议: yagmail

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM