I've got a simple SMTP mailing example from here and my modified it. My code is:
import smtplib
sender = 'igor.savinkin#gmail.com'
receivers = ['igor.savinkin#gmail.com']
message = """From: From Igor <igor.savinkin#gmail.com>
To: To Igor Savinkin <igor.savinkin#gmail.com>
Subject: SMTP e-mail test
This is a test e-mail message from SMTP python.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email to " + receivers.__str__()
except SMTPException:
print "Error: unable to send email"
Output is:
Successfully sent email to ['igor.savinkin#gmail.com']
Yet, in actuality I find no mails like these in my inbox. The spam folder is checked too!
What's wrong? I use rhc (OpenShift) platform.
You send your mail to a local SMTP server (smtpObj = smtplib.SMTP('localhost')). IMHO it accepts it (request is syntactically correct) but is then not allowed (or not configured) to forward it to gmail. I'm not using OpenShift so I do not know how SMTP is configured there.
You should control how the local SMTP server is configured.
Related
I have tried a simple email script in python to understand the functioning. The code is
import smtplib
sender = 'avin#gmail.com'
receivers = ['avin.b#vipointsolutions.net']
message = "This is a test e-mail message."
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print("Successfully sent email")
except Exception:
print("error")
When i try to run this i got the message Successfully sent email but the email is not delivered to my inbox.I have set up postfix running on my local machine at port 25.Can anyone guide me with the reason on why the email is not receiving.Is it because of the code? Any help would be appreciated.
You have to provide SMTP of the email sender and you have to login from the sender email.
example:
sender = 'avin#gmail.com'
receivers = 'avin.b#vipointsolutions.net'
msg_format = "Hello, Test email"
server = smtplib.SMTP('smtp.office365.com')
server.starttls()
server.verify(receivers)
server.login(sender, 'password')
server.sendmail(sender, receivers, msg_format)
server.quit()
print("Successfully sent email")
I have a python code which crawls some websites and send me some emails.
The code is working fine on my computer. Now I am trying to run the same code on an Amazon web server. However, google blocks the code. Is there any workaround?
import smtplib
# Send email to my personal email address
def send_email(subject, msg):
try:
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login('e******#gmail.com', 'S****')
message = 'Subject: {}\n\n{}'.format(subject, msg)
server.sendmail('e*#gmail.com', 'e*#gmail.com', message)
server.quit()
print("Success: Email sent!")
except:
print("Email failed to send.")
As answered in the comment section by Furas, Gmail may blocks access from untrusted programs and the programmer may have to create a separated password for these programs. Allow less secure apps to access your Gmail account
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
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
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"
I am using smtplib and I am sending notification emails from my application. However I noticed that sometimes (especially when there is a lot of idle time between mail sending) I get a SMTPServerDisconnected error.
I guess there are 2 solutions for this (know none of them, though)
Increase idle time between sending mails
reconnect when connection is down.
I think 2nd solution seems more elegant. But how can I do that?
edit: I am adding the code
from smtplib import SMTP
smtp = SMTP()
smtp.connect('smtp.server.com')
smtp.login('username','password')
def notifyUser():
smtp.sendmail(from_email, to_email, msg.as_string())
Yes, you can check if the connection is open. To do this, issue a NOOP command and test for status == 250. If not, then open the connection before sending out your mail.
def test_conn_open(conn):
try:
status = conn.noop()[0]
except: # smtplib.SMTPServerDisconnected
status = -1
return True if status == 250 else False
def send_email(conn, from_email, to_email, msg):
if not test_conn_open(conn):
conn = create_conn()
conn.sendmail(from_email, to_email, msg.as_string())
return conn # as you want are trying to reuse it.
Note that you are doing this as opening a connection, say with gmail, consumes time, like 2-3 secs. Subsequently, to optimize on sending multiple emails that you may have at hand, then you should also follow Pedro's response (last part).
If your use case is sending a single message at a time, the solution that seems most correct to me, would be to create a new SMTP session for each message:
from smtplib import SMTP
smtp = SMTP('smtp.server.com')
def notifyUser(smtp, smtp_user, smtp_password, from_email, to_email, msg):
smtp.login(smtp_user, smtp_password)
smtp.sendmail(from_email, to_email, msg.as_string())
smtp.quit()
If your SMTP server doesn't required that you authenticate yourself (a common case), this can be further simplified to:
from smtplib import SMTP
smtp = SMTP('smtp.server.com')
def notifyUser(smtp, from_email, to_email, msg):
smtp.sendmail(from_email, to_email, msg.as_string())
smtp.quit()
If it is common to have more than one message to send at once, and you want to optimise this case by reusing the same SMTP session for the group of messages (can be simplified as above if you don't need to login to the SMTP server):
from smtplib import SMTP
smtp = SMTP('smtp.server.com')
def notifyUsers(smtp, smtp_user, smtp_password, from_to_msgs):
"""
:param from_to_msgs: iterable of tuples with `(from_email, to_email, msg)`
"""
smtp.login(smtp_user, smtp_password)
for from_email, to_email, msg in from_to_msgs:
smtp.sendmail(from_email, to_email, msg.as_string())
smtp.quit()
This maybe a repeated question but I'm still facing issues on this, hope there's a solution around. Thanks in advance.
I'm trying to send mail through the company's server
I'm currently using Python version 2.6 and Ubuntu 10.04
This is the error message I got
Traceback (most recent call last):
File "hxmass-mail-edit.py", line 227, in <module>
server.starttls()
File "/usr/lib/python2.6/smtplib.py", line 611, in starttls
raise SMTPException("STARTTLS extension not supported by server.") smtplib.SMTPException: STARTTLS extension not supported by server.
Here goes part of the code
server = smtplib.SMTP('smtp.abc.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.ehlo()
server.login('sales#abc.com', 'abc123')
addressbook=sys.argv[1]
Remove the ehlo() before starttls().
starttls() + ehlo() results in two HELLO messages, which cause the server remove the STARTTLS in the reply message.
server = smtplib.SMTP('smtp.abc.com', 587)
server.starttls()
server.ehlo()
server.login('sales#abc.com', 'abc123')
I had a similar issue trying to send a mail through the company's server (without autentication needed)
I solved removing the server.ehlo and removing the port number:
server = smtplib.SMTP("smtp.mycompany.com")
server.sendmail(fromaddr, toaddr, text)
removing server.ehlo() before server.starttls() helped me get my code working! Thank you, Leonard!
my code:
s = smtplib.SMTP("smtp.gmail.com",587)
s.starttls()
s.ehlo
try:
s.login(gmail_user, gmail_psw)
except SMTPAuthenticationError:
print 'SMTPAuthenticationError'
s.sendmail(gmail_user, to, msg.as_string())
s.quit()
The error says it all, it seems the SMTP server sou are using doesn't support STARTTLS and you aru issuing server.starttls(). Try using the server without calling server.starttls().
Without more info is the only I can say.
I am able to resolve the issue with below code, by adding port number with server name:
server = smtplib.SMTP('smtp.abc.com:587')
from smtplib import SMTP_SSL, SMTP, SMTPAuthenticationError
from ssl import create_default_context
from email.message import EmailMessage
sender = 'aaa#bbb.com'
description = "This is the test description supposed to be in body of the email."
msg = EmailMessage()
msg.set_content(description)
msg['Subject'] = 'This is a test title'
msg['From'] = f"Python SMTP <{sender}>"
msg['To'] = 'bbb#ccc.com'
def using_ssl():
try:
server = SMTP_SSL(host='smtp.gmail.com', port=465, context=create_default_context())
server.login(sender, password)
server.send_message(msg=msg)
server.quit()
server.close()
except SMTPAuthenticationError:
print('Login Failed')
def using_tls():
try:
server = SMTP(host='smtp.gmail.com', port=587)
server.starttls(context=create_default_context())
server.ehlo()
server.login(sender, password)
server.send_message(msg=msg)
server.quit()
server.close()
except SMTPAuthenticationError:
print('Login Failed')
By testing and researching myself, I found out that the gmail servers do not use tls connections with python anymore.
You must not use service.startttls(). Gmail service do not support this type of connection anymore.
Also remember to use the SMTP ports (mail reserved ports) for sending emails.
POP3 and IMAP ports for receiving email.
s_u = "Test"
service = smtplib.SMTP_SSL("smtp.gmail.com", 465)
service.ehlo()
service.sendmail("SENDER_EMAIL","RECEIVER_EMAIL","MESSAGE")
You can't send the email even if you put the correct credentials,
look at this: Login credentials not working with Gmail SMTP
Are you sure that you want to encrypt (StartTLS) the connection to the mail server? I would contact someone who knows the insides of that server to see what protocol/encryption to use.
You say that upon removing the call to server.starttls(), you get a different series of error messages. Could you please post those messages as well?
Also, you might want to read up on StartTLS so you understand what it is and why you would want to use it. It seems you're writing a Serious Business program, in which case you'll probably want to understand what you are doing, security-wise.
Yes putting server.starttls() above server.ehlo() solved this.