ineedhelp
ineedhelp

Reputation: 21

Sending email with python script

What I'm trying to do is get my python code to send an email. This code is supposed to use the yahoo smtp to send the email. I don't need any attachments or anything else. The code bugs out where it says 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 = ['[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)

Upvotes: 2

Views: 1615

Answers (2)

PascalVKooten
PascalVKooten

Reputation: 21433

As developer I suggest: yagmail

Upvotes: 1

Narusan
Narusan

Reputation: 502

I don't know about Yahoo, but Google blocked the login via their smtp-port. 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.

Upvotes: 1

Related Questions