Unable to send error log email using smptlib and loggings, Python - python-2.7

Hi I am trying to send an email to myself when an exception is raised. However I am getting an exception I don't know how to solve. Here is the code and exception. I have tried all SO answers but in vain
import logging
import logging.handlers
import smtplib
s = smtplib.SMTP_SSL("smtp.gmail.com", 587)
s.login('xyz#gmail.com', 'myPassword')
s.starttls()
logger = logging.getLogger()
logger.addHandler(s)
try:
a = 2/0
except Exception as e:
logger.exception('Unhandled Exception')
s.sendmail('xyz#gmail.com', 'xyz#gmail.com', 'Hi')
s.close()
ERROR LOG:
Traceback (most recent call last): File "try.py", line 5, in
s = smtplib.SMTP_SSL("smtp.gmail.com", 587)
File "/usr/lib/python2.7/smtplib.py", line 788, in init
SMTP.init(self, host, port, local_hostname, timeout)
File "/usr/lib/python2.7/smtplib.py", line 256, in init
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 794, in _get_socket
new_socket = ssl.wrap_socket(new_socket, self.keyfile, self.certfile)
File "/usr/lib/python2.7/ssl.py", line 487, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 243, in init
self.do_handshake()
File "/usr/lib/python2.7/ssl.py", line 405, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [Errno 1] _ssl.c:510: error:140770FC:SSL
routines:SSL23_GET_SERVER_HELLO:unknown protocol
Thanks for help in advance.

587 is a non-SSL port and hence SMTP_SSL call is failing. Try using port 465 as
smtplib.SMTP_SSL("smtp.gmail.com", 465)
or use the method for port 587
smtplib.SMTP("smtp.gmail.com", 587)

Related

Name or service not known using AWS SES in Airflow

I am trying to send emails on failures in airflow and I get:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/airflow/models/taskinstance.py", line 1475, in email_alert
send_email(self.task.email, subject, html_content)
File "/usr/local/lib/python3.6/dist-packages/airflow/utils/email.py", line 60, in send_email
mime_subtype=mime_subtype, mime_charset=mime_charset, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/airflow/utils/email.py", line 106, in send_email_smtp
send_MIME_email(smtp_mail_from, recipients, msg, dryrun)
File "/usr/local/lib/python3.6/dist-packages/airflow/utils/email.py", line 126, in send_MIME_email
s = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT) if SMTP_SSL else smtplib.SMTP(SMTP_HOST, SMTP_PORT)
File "/usr/lib/python3.6/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.6/smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python3.6/smtplib.py", line 307, in _get_socket
self.source_address)
File "/usr/lib/python3.6/socket.py", line 704, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "/usr/lib/python3.6/socket.py", line 745, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
airflow.cfg looks like:
[email]
email_backend = airflow.utils.email.send_email_smtp
[smtp]
smtp_host = aws.mailing.company.com
smtp_starttls = True
smtp_ssl = False
smtp_user = XXXXXX
smtp_password = YYYYYY
smtp_port = 587
smtp_mail_from = name#aws.mailing.company.com
What does Name or service not known mean? Its that smtp_host is not correct or could be something else?

Send email with django + gunicorn + nginx get timeout

I'm trying to deploy a Django project in AWS with gunicorn + nginx but I'm getting a timeout error. My email backend uses AWS SES with SMTP authentication.
The first 2 emails are sent normally, after these I'm getting this error.
The account is already an unblocked restriction for sending an email.
Local django development server works fine, it sends emails normally. In local virtual machine with same EC2 specs sends emails normally.
Running in django shell I'm getting this log at third email sent:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "<console>", line 5, in sendE
File "/home/ubuntu/myproj/share/forms.py", line 23, in share_email
email_message.send()
File "/home/ubuntu/.local/share/virtualenvs/myproj-rqmaW6Yv/lib/python3.7/site-packages/django/core/mail/message.py", line 291, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/ubuntu/.local/share/virtualenvs/myproj-rqmaW6Yv/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages
new_conn_created = self.open()
File "/home/ubuntu/.local/share/virtualenvs/myproj-rqmaW6Yv/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 63, in open
self.connection = self.connection_class(self.host, self.port, **connection_params)
File "/usr/lib/python3.7/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.7/smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python3.7/smtplib.py", line 307, in _get_socket
self.source_address)
File "/usr/lib/python3.7/socket.py", line 727, in create_connection
raise err
File "/usr/lib/python3.7/socket.py", line 716, in create_connection
sock.connect(sa)
TimeoutError: [Errno 110] Connection timed out
```
Any idea?
Ok after testing a lot, I Found EC2 instances have a restriction over default smtp port connection. Change the port from 25 to 587 and it works perfectly.
More info: https://aws.amazon.com/es/premiumsupport/knowledge-center/smtp-connectivity-timeout-issues-ses/

Django send-mail [Errno -2] Name or service not known

I have problem in sending mail in Django
I set my gmail following this link:
https://support.google.com/mail/answer/7126229?visit_id=1-636278779262945155-948643181&rd=1#cantsignin
And i tried every solution online but still get [Errno -2]
I found someone said it is because the DNS problem ,can some one tell me what is wrong with my code and is there any solution ?
views.py
import django
from django import settings
from django.core.mail import send_mail
def contact(request):
send_mail('subject','message',settings.EMAIL_HOST_USER,['zwt467875460#gmail.com'],fail_silently = False)
return HttpResponseRedirect('/contact/thanks')
def thanks(request):
return HttpResponse('thanks!')
settings.py
#email config
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gamil.com'
EMAIL_PORT = 587
EMAIL_HOST_USER='zwt467875460#gmail.com'
EMAIL_HOST_PASSWORD='*********' #my gmail password
EMAIL_USER_TLS = True
DEFAULT_FORM_EMAIL = EMAIL_HOST_USER
ACCOUNT_EMAIL_VERIFICATION = 'none'
traceback error
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/wenting/WTDjango/mysite/books/views.py", line 30, in contact
send_mail('subject','message',settings.EMAIL_HOST_USER,['zwt467875460#gmail.com'],fail_silently = False)
File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/mail/__init__.py", line 62, in send_mail
return mail.send()
File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/mail/message.py", line 342, in send
return self.get_connection(fail_silently).send_messages([self])
File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/mail/backends/smtp.py", line 100, in send_messages
new_conn_created = self.open()
File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/mail/backends/smtp.py", line 58, in open
self.connection = connection_class(self.host, self.port, **connection_params)
File "/usr/lib/python2.7/smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 291, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 557, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
gaierror: [Errno -2] Name or service not known
[15/Apr/2017 18:45:56] "GET /contact/ HTTP/1.1" 500 102295
and in the Django error page:
Exception Location: /usr/lib/python2.7/socket.py in create_connection, line 557
I guess my problem is that Gmail think i dont have a fixed or right DNS
so i cant create a socket
And then i tried sendmail :
after install sendmail ,sendmail-cf,and configure it ,
i tried :
echo "Subject: sendmail test" | sendmail -v zwt467875460#gmail.com
and the output is (i omit the sending details):
354 Enter mail, end with "." on a line by itself
>>> .
050 <zwt467875460#gmail.com>... Connecting to smtp.gmail.com via relay...
050 <zwt467875460#gmail.com>... Deferred: Connection refused by smtp.gmail.com
250 2.0.0 v3GKMtLU003555 Message accepted for deliveryzwt467875460#gmail.com... Sent (v3GKMtLU003555 Message accepted for delivery)
Closing connection to [127.0.0.1]
>>> QUIT
221 2.0.0 localhost.localdomain closing connection
The connection is refused by smtp.gmail.com
Check if IMAP/POP are enabled from your Gmail account settings.
Also check that access to 'less secure apps' is enabled .
If not, follow the link :https://support.google.com/accounts/answer/6010255

django mail webform not connection to mail server

I spent a lot of time developing the form and connecting all the pieces together and now I cannot connect to my smtp server through django settings. Here are my settings...
DEFAULT_FROM_EMAIL = 'auto#domain.com'
EMAIL_HOST = 'smtp.mailhost.com'
EMAIL_HOST_USER = 'auto#domain.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_USE_TLS = True
EMAIL_PORT = 465
I tried to send it through my form and it didn't work so I tried to send one through the shell..
from django.core.mail import send_mail
send_mail('subject','message','auto#domain.com', ['me#domain.com'], fail_silently=False)
and I get this traceback...
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/core/mail/__init__.py", line 62, in send_mail
return mail.send()
File "/usr/local/lib/python2.7/dist-packages/django/core/mail/message.py", line 286, in send
return self.get_connection(fail_silently).send_messages([self])
File "/usr/local/lib/python2.7/dist-packages/django/core/mail/backends/smtp.py", line 92, in send_messages
new_conn_created = self.open()
File "/usr/local/lib/python2.7/dist-packages/django/core/mail/backends/smtp.py", line 50, in open
self.connection = connection_class(self.host, self.port, **connection_params)
File "/usr/lib/python2.7/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 312, in connect
(code, msg) = self.getreply()
File "/usr/lib/python2.7/smtplib.py", line 363, in getreply
raise SMTPServerDisconnected("Connection unexpectedly
closed")
SMTPServerDisconnected: Connection unexpectedly closed
You should recheck the data you use: login, password, etc.
If it doesn't help, try to use port 587.
SMTP uses this one. I hope it will help.
495 is now deprecated.

Configuring Django/Pinax Email

I'm trying to configure automated emails for my Pinax app.
In the shell (python manage.py shell) I am doing the following to test my email settings:
>>> send_mail ('Test','Test','myemail#myemail.com',['myemail#myemail.com'])
However I am getting the follow traceback:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/myname/Desktop/myenv2/lib/python2.7/site-packages/django/core/mail/__init__.py", line 61, in send_mail
connection=connection).send()
File "/Users/myname/Desktop/myenv2/lib/python2.7/site-packages/django/core/mail/message.py", line 175, in send
return self.get_connection(fail_silently).send_messages([self])
File "/Users/myname/Desktop/myenv2/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 78, in send_messages
new_conn_created = self.open()
File "/Users/myname/Desktop/myenv2/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 41, in open
local_hostname=DNS_NAME.get_fqdn())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 242, in __init__
(code, msg) = self.connect(host, port)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 302, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 277, in _get_socket
return socket.create_connection((port, host), timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 571, in create_connection
raise err
error: [Errno 60] Operation timed out
My email settings in settings.py are as follow:
# These are the email settings for sending out confirmation emails, alerts,etc.
DEFAULT_FROM_EMAIL = 'Mysite <myemail#myemal.com>'
EMAIL_USE_TLS = True
EMAIL_HOST = 'box401.bluehost.com'
EMAIL_HOST_USER = 'myemail#myemal.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
EMAIL_SUBJECT_PREFIX = '[Your Site] '
Any insight into what could be wrong? I checked my password and the settings with the host and they seem fine.