diggers3
diggers3

Reputation: 229

Sending an Email with Python Issue

I have this code and I cannot seem to get it to work. When I run it, the script doesn't finish in IDLE unless I kill it manually. I have looked all over and rewritten the code a few times, and no luck.

import smtplib

SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587

sender = '[email protected]'
password = '123'
recipient = '[email protected]'
subject = 'Test Results'
body = """** AUTOMATED EMAIL ** \r\n Following are
            the test results:  \r\n"""

headers = ["From: " + sender,
           "Subject: " + subject,
           "To: " + recipient]
headers = "\r\n".join(headers)

try:
      session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
      session.ehlo()
      session.starttls()
      session.ehlo()
      session.login(sender, password)
      session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
except smtplib.SMTPException:
      print "Error: Unable to send email."

session.quit()

Upvotes: 1

Views: 945

Answers (1)

brandonscript
brandonscript

Reputation: 73024

Not sure why you're using ehlo; contrary to popular opinion, it's not actually required so long as you set the headers correctly. Here's a tested and working script -- it works on *nix and OSX. Since you're using Windows though, we need to troubleshoot further.

import smtplib, sys

def notify(fromname, fromemail, toname, toemail, subject, body, password):
    fromaddr = fromname+" <"+fromemail+">"
    toaddrs = [toname+" <"+toemail+">"]
    msg = "From: "+fromaddr+"\nTo: "+toemail+"\nMIME-Version: 1.0\nContent-type: text/plain\nSubject: "+subject+"\n"+body

    # Credentials (if needed)
    username = fromemail
    password = password

    # The actual mail send
    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.starttls()
        server.login(username,password)
        server.sendmail(fromaddr, toaddrs, msg)
        server.quit()       
        print "success"
    except smtplib.SMTPException:
        print "failure"

fromname = "Your Name"
fromemail = "[email protected]"        
toname = "Recipient"
toemail = "[email protected]"
subject = "Test Mail"
body = "Body....."

notify(fromname, fromemail, toname, toemail, subject, body, password)

Upvotes: 2

Related Questions