Member Avatar for sravan953

Hey guys,

I wanted to make a simple Python program to send an email to my Gmail account. So:

import smtplib
sobj=smtplib.SMTP("smtp.gmail.com")
sender="sravan953@gmail.com"
rec="sravan953@gmail.com"
msg="""
From: From Person<sravan953@gmail.com>
To: To Person<sravan953@gmail.com>
Subject: Test
Does it work?
"""
sobj.sendmail(sender,rec,msg)

-but it doesn't work, it shows an error

Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    smtpobj.sendmail(sender,rec,msg)
  File "C:\Python26\lib\smtplib.py", line 698, in sendmail
    raise SMTPSenderRefused(code, resp, from_addr)
SMTPSenderRefused: (530, '5.7.0 Must issue a STARTTLS command first. m25sm8001489waf.9', 'sravan953@gmail.com')

What's wrong and what is happening?

Thanks a lot guys!

Recommended Answers

All 11 Replies

I think something like this should work:

import smtplib

s = smtplib.SMTP('smtp.gmail.com', 465)
myGmail = mygmail@gmail.com
myGMPasswd = mygmailpassword
recipient = recipient@gmail.com
message = """Your message"""
s.ehlo()
s.starttls()
s.login(myGmail, myGMPasswd)
s.sendmail(myGmail,
recipient,
message)
s.quit()

Did it help? or did i something wrong?

Dan08

Member Avatar for sravan953

Thanks Dan08,

On modifying your code a little, it worked, all I did was that I removed the s.ehlo() (what's it even for?).

Thanks

On modifying your code a little, it worked, all I did was that I removed the s.ehlo() (what's it even for?).

Well, I think you dont really need it, but anyway, i found this:

"SMTP.ehlo([hostname])

Identify yourself to an ESMTP server using EHLO. The hostname argument defaults to the fully qualified domain name of the local host. Examine the response for ESMTP option and store them for use by has_extn(). Also sets several informational attributes: the message returned by the server is stored as the ehlo_resp attribute, does_esmtp is set to true or false depending on whether the server supports ESMTP, and esmtp_features will be a dictionary containing the names of the SMTP service extensions this server supports, and their parameters (if any).

Unless you wish to use has_extn() before sending mail, it should not be necessary to call this method explicitly. It will be implicitly called by sendmail() when necessary."

From: http://docs.python.org/library/smtplib.html


Hope this can help you, Dan08.

Member Avatar for sravan953

I now wanted to modify the code a little bit and take it one step further:

import smtplib

sen="sravan953@gmail.com"
print("From: "+sen)
rec=raw_input("To: ")

dom=""

n=0
for x in rec:
    if(x=='@'):
        ext=rec[n:]
    n+=1

if(ext=="gmail.com"):
    dom="smtp.gmail.com"
elif(ext=="yahoo.co.in" or ext=="yahoo.com"):
    dom="smtp.yahoo.com"
    
sub=raw_input("\nSubject: ")

msg="To: "+rec+"\nSubject: "+sub+"\n"+raw_input("\nYour message here:\n")

user="sravan953"
passw="jamklop127"

s=smtplib.SMTP(dom,587)
s.starttls()
s.login(user,passw)

try:
    s.sendmail(sen, rec,msg)
    print("\nSuccess")
    s.quit()
except:
    print("\nFailed")

raw_input("<Any key to quit>")

When I try to run the above code irrespective of whether I use a 'To' Gmail ID or Yahoo! ID, it shows this error message:

Traceback (most recent call last):
  File "C:\Documents and Settings\Sravan\My Documents\Sravan\PYTHON\smtp.py", line 28, in <module>
    s.starttls()
  File "C:\Python26\lib\smtplib.py", line 609, in starttls
    self.ehlo_or_helo_if_needed()
  File "C:\Python26\lib\smtplib.py", line 509, in ehlo_or_helo_if_needed
    if not (200 <= self.ehlo()[0] <= 299):
  File "C:\Python26\lib\smtplib.py", line 382, in ehlo
    self.putcmd(self.ehlo_msg, name or self.local_hostname)
  File "C:\Python26\lib\smtplib.py", line 318, in putcmd
    self.send(str)
  File "C:\Python26\lib\smtplib.py", line 310, in send
    raise SMTPServerDisconnected('please run connect() first')
SMTPServerDisconnected: please run connect() first
import smtplib

sen="sravan953@gmail.com"
print("From: "+sen)
rec=raw_input("To: ")

dom=""

n=0
for x in rec:
    if(x=='@'):
        ext=rec[n:]
    n+=1

if(ext=="gmail.com"):
    dom="smtp.gmail.com"
elif(ext=="yahoo.co.in" or ext=="yahoo.com"):
    dom="smtp.yahoo.com"
    
sub=raw_input("\nSubject: ")

msg="To: "+rec+"\nSubject: "+sub+"\n"+raw_input("\nYour message here:\n")

user="sravan953"
passw="jamklop127"

s=smtplib.SMTP(dom,587)
s.starttls()
s.login(user,passw)

try:
    s.sendmail(sen, rec,msg)
    print("\nSuccess")
    s.quit()
except:
    print("\nFailed")

raw_input("<Any key to quit>")

Instead of dom="smtp.yahoo.com", try dom="smtp.mail.yahoo.com".
Thats the first thing that looks wrong.

commented: thanks for helping +8
Member Avatar for sravan953

Oh! I'll try that and get back to you.. :)

Member Avatar for sravan953

Sorry Dan08, it didn't work either. :(

So what basically you want build is a email sender, that send emails from gmail accounts and yahoo acount, isnt it?

So i built this program for you, it seems a bit strange but i think is working perfectly. Have a look and then say something:

import smtplib
def gmail():
    print("CONNECTING TO GMAIL")
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        print("CONNECTED")
        print("STARTING SECURE CONNECTION")
        try:
            server.starttls()
            print("SECURED CONNECTION REACHED")
        except:
            print("WARNING: ITS NOT SAFE SEND THIS EMAIL")
        gmailUser = str(raw_input("USERNAME: "))
        gmailPasswd = str(raw_input("PASSWORD: "))
        print("CHECKING USERNAME AND PASSWORD")
        try:
            server.login(gmailUser, gmailPasswd)
            print("YOUR USERNAME AND PASSWORD ARE CORRECT")
        except:
            print("YOUR USERNAME, PASSWORD OR BOTH IS INCORRECT")
            quit
        recipient = str(raw_input("RECIPIENT: "))
        message = str(raw_input("MESSAGE:\n"))
        print("SENDING EMAIL")
        try:
            server.sendmail(gmailUser, recipient, message)
            print("MESSAGE SENT FROM: " + gmailUser)
            quit
        except:
            print("AN ERROR OCCURED WHILE SENDING YOUR E-MAIL")
            quit
    except:
        print("CANNOT CONNECT TO GMAIL")
        quit
def yahoo():
    print("CONNECTING TO YAHOO")
    try:
        server = smtplib.SMTP("smtp.mail.yahoo.com", 587)
        print("CONNECTED")
        print("STARTING SECURE CONNECTION")
        try:
            server.starttls()
            print("SECURED CONNECTION REACHED")
        except:
            print("WARNING: ITS NOT SAFE SEND THIS EMAIL")
        yahooUser = str(raw_input("USERNAME: "))
        yahooPasswd = str(raw_input("PASSWORD: "))
        print("CHECKING USERNAME AND PASSWORD")
        try:
            server.login(yahooUser, yahooPasswd)
            print("YOUR USERNAME AND PASSWORD ARE CORRECT")
        except:
            print("YOUR USERNAME, PASSWORD OR BOTH IS INCORRECT")
            quit
        recipient = str(raw_input("RECIPIENT: "))
        message = str(raw_input("MESSAGE:\n"))
        print("SENDING EMAIL")
        try:
            server.sendmail(yahooUser, recipient, message)
            print("MESSAGE SENT FROM: " + yahooUser)
            quit
        except:
            print("AN ERROR OCCURED WHILE SENDING YOUR E-MAIL")
            quit
    except:
        print("CANNOT CONNECT TO YAHOO")
        quit
choice = str(raw_input("IM Network? GMAIL/YAHOO: "))
if choice == "GMAIL":
    gmail()
elif choice == "YAHOO":
    yahoo()
else:
    print("IM NETWORK NOT RECOGNISED")
    quit

See if this program can help you, and then tell me somethin', the best from Dan08.

Member Avatar for sravan953

Hey Dan08,

The Yahoo! part of the code still doesn't work for me! ;_(
I have now perfected sending emails from a Gmail account with a proper 'To, From & Subject' thanks to you! :)

Regarding the Yahoo! issue, I anyways don't use it, I just wanted to add it to my program to increase it's flexibility. Thanks mate! ;)

Hey there dude, I just wanted to let you know that you displayed your gmail account username and password.
I would change it NOW :S

best regards.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.