0

i am new to python, when am trying to sending mail by using python my program is bellow

import smtplib
from smtplib import SMTP

sender = 'raju.ab@gmail.com'
receivers = ['sudeer.p@eunoia.in']

message = """ this message sending from python
for testing purpose
"""

try:
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.ehlo()
smtpObj.login(username,password)
smtpObj.sendmail(sender, receivers, message)
smtpObj.quit()
print "Successfully sent email"
except smtplib.SMTPException:

print "Error: unable to send email"

when i execute it shows Error: unable to send mail message, how to send email in python please explain

Raju Abe
  • 735
  • 2
  • 10
  • 25
  • 2
    *"it shows Error: unable to send mail message"* - that's exactly what you've asked it to do! If you didn't wrap the whole process in a `try`, you would get a more specific error message that gave you more information about the problem. – jonrsharpe Dec 03 '14 at 13:01

2 Answers2

2

as is said here: How to send an email with Gmail as provider using Python?

This code works. But GMAIL wil warn you if you want to allow this script send the email or not. Sign in in your account, and accesss this URL: https://www.google.com/settings/security/lesssecureapps

import smtplib
gmail_user = "yourmail@gmail.com"
gmail_pwd = "mypassword"
FROM = 'yourmail@gmail.com'
TO = ['receiber@email.com'] #must be a list
SUBJECT = "Testing sending using gmail"
TEXT = "Testing sending mail using gmail servers"
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
  #server = smtplib.SMTP(SERVER) 
  server = smtplib.SMTP("smtp.gmail.com", 587) #or port 465 doesn't seem to work!
  server.ehlo()
  server.starttls()
  server.login(gmail_user, gmail_pwd)
  server.sendmail(FROM, TO, message)
  #server.quit()
  server.close()
  print 'successfully sent the mail'
except:
  print "failed to send mail"
Community
  • 1
  • 1
2

What i have done in code :

1.Added a error object to get the error message

import smtplib
from smtplib import SMTP       

try:
    sender = 'xxx@gmail.com'
    receivers = ['xxx.com']

    message = """ this message sending from python
    for testing purpose
    """
    smtpObj = smtplib.SMTP(host='smtp.gmail.com', port=587)
    smtpObj.ehlo()
    smtpObj.starttls()
    smtpObj.ehlo()
    smtpObj.login('xxx','xxx')
    smtpObj.sendmail(sender, receivers, message)
    smtpObj.quit()
    print "Successfully sent email"
except smtplib.SMTPException,error:
    print str(error)
    print "Error: unable to send email"

If u ran this code u would see a error message like this stating that google is not allowing u to login via code

Things to change in gmail:

1.Login to gmail

2.Go to this link https://www.google.com/settings/security/lesssecureapps

3.Click enable then retry the code

Hopes it help :)

But there are security threats if u enable it

The6thSense
  • 8,103
  • 8
  • 31
  • 65