Whenever I call the method below from views.py with the email settings shown below, two copies of the email are sent to the recipient and I get the error shown below:
def sendEmailBasic(request):
msg = EmailMessage('Request Callback',
'Here is the message.', to=['example#gmail.com'])
msg.send()
return HttpResponseRedirect('/')
Exception happened during processing of request from ('127.0.0.1', 58207)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 593, in process_request_thread
self.finish_request(request, client_address)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 150, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 651, in __init__
self.finish()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 710, in finish
self.wfile.close()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 279, in close
self.flush()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
DEFAULT_FROM_EMAIL = 'myemail#gmail.com'
SERVER_EMAIL = 'myemail#gmail.com'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = 'my password'
Browsers will often send a HEAD request to any URL they can find. If Django operates on the HEAD request, then again on the following GET request, you'll see functions being called twice.
Consider moving the "send mail" function to a POST request, or only send email on a real GET, not anything else.
Untested:
def sendEmailBasic(request):
if request.method in ('GET', 'POST'):
msg = EmailMessage('Request Callback',
'Here is the message.', to=['example#gmail.com'])
msg.send()
return HttpResponseRedirect('/')
See also: http://restcookbook.com/HTTP%20Methods/idempotency/
Related
I used Celery for email registration asynchronously, but when I trigger this asynchronous request, the following error will appear
Traceback (most recent call last):
File "d:\python3\lib\site-packages\dns\resolver.py", line 982, in nameservers
raise NotImplementedError
NotImplementedError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\python3\lib\site-packages\celery\app\trace.py", line 451, in trace_task
R = retval = fun(*args, **kwargs)
File "d:\python3\lib\site-packages\celery\app\trace.py", line 734, in __protected_call__
return self.run(*args, **kwargs)
File "E:\Exploit_blog\blog_index_html\tasks.py", line 9, in send_email
send_mail(
File "d:\python3\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail
return mail.send()
File "d:\python3\lib\site-packages\django\core\mail\message.py", line 284, in send
return self.get_connection(fail_silently).send_messages([self])
File "d:\python3\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages
new_conn_created = self.open()
File "d:\python3\lib\site-packages\django\core\mail\backends\smtp.py", line 62, in open
self.connection = self.connection_class(self.host, self.port, **connection_params)
File "d:\python3\lib\smtplib.py", line 1034, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout,
File "d:\python3\lib\smtplib.py", line 253, in __init__
(code, msg) = self.connect(host, port)
File "d:\python3\lib\smtplib.py", line 339, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "d:\python3\lib\smtplib.py", line 1040, in _get_socket
new_socket = super()._get_socket(host, port, timeout)
File "d:\python3\lib\smtplib.py", line 310, in _get_socket
return socket.create_connection((host, port), timeout,
File "d:\python3\lib\site-packages\eventlet\green\socket.py", line 44, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "d:\python3\lib\site-packages\eventlet\support\greendns.py", line 543, in getaddrinfo
qname, addrs = _getaddrinfo_lookup(host, family, flags)
File "d:\python3\lib\site-packages\eventlet\support\greendns.py", line 505, in _getaddrinfo_lookup
answer = resolve(host, qfamily, False, use_network=use_network)
File "d:\python3\lib\site-packages\eventlet\support\greendns.py", line 450, in resolve
return _proxy.query(name, rdtype, raise_on_no_answer=raises,
File "d:\python3\lib\site-packages\eventlet\support\greendns.py", line 394, in query
step(self._resolver.query, qname, rdtype, rdclass, tcp, source, raise_on_no_answer=False)
File "d:\python3\lib\site-packages\eventlet\support\greendns.py", line 334, in _resolver
self.clear()
File "d:\python3\lib\site-packages\eventlet\support\greendns.py", line 342, in clear
self._resolver = dns.resolver.Resolver(filename=self._filename)
File "d:\python3\lib\site-packages\dns\resolver.py", line 756, in __init__
self.read_registry()
File "d:\python3\lib\site-packages\dns\resolver.py", line 858, in read_registry
self.nameservers = info.nameservers
File "d:\python3\lib\site-packages\dns\resolver.py", line 984, in nameservers
raise ValueError(f'nameserver {nameserver} is not an '
ValueError: nameserver ; is not an IP address or valid https URL
There is no problem with the celery tasks code, because I was able to use it before, but the above situation appeared after I changed a computer
tasks code
from django.core.mail import send_mail
from celery import shared_task
# 发送邮件验证码,使用task进行异步处理,获取从视图层获取来的值,然后发送到用户邮箱中
#shared_task
def send_email(request, rand_str):
send_mail(
subject='验证码',
message='你的验证码为:' + rand_str + '请不要将你的验证码告诉其他人',
from_email='TEXT',
recipient_list=[request],
fail_silently=False
)
return (request, rand_str)
main settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'xxx'
EMAIL_HOST_PASSWORD = 'xxx'
.> celery exchange=celery(direct) key=celery
Celery startup console can recognize this tasks
[tasks]
. Let.tasks.add
. blog_index_html.tasks.send_email
When I searched for a few days, I determined the BUG location, it turned out that the eventlet and dnspython modules were incompatible, and I found a solution in his official GIT repository.
My operation is to uninstall and reinstall the dnspython module
github link
I'm trying to send an actual email to myself from my website using send_mail. I had used localhost and the following cmd command,
python -m smtpd -n -c DebuggingServer localhost:1025
in order to test it. It intercepts with no problem, but I don't see anything in my inbox.
My email provider works with SSL, so I turned it to True and enabled 'access to the mailbox using mail clients' in my mail settings.
Here is the settings.py file:
EMAIL_HOST = '178.68.164.41' # My current ip address
EMAIL_PORT = '465' # Port of the email host
EMAIL_HOST_USER = 's...6#rambler.ru' # Here is my actual email
EMAIL_HOST_PASSWORD = '.....' # Here is my actual password from my email login
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True
Here is the views.py file:
from django.shortcuts import render
from django.core.mail import send_mail
from .forms import ContactForm
def contact(request):
form = ContactForm
if request.method == 'POST':
message_name = request.POST.get('name')
message_email = request.POST.get('email')
message = request.POST.get('message')
send_mail(message_name, message, message_email, ['s****6#rambler.ru'])
return render(request, 'contact.html', {'form': form})
Here's the exception:
Internal Server Error: /contact/
Traceback (most recent call last):
File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\1\PycharmProjects\StasProject\sales_project\contact\views.py", line 12, in contact
send_mail(message_name, message, message_email, ['sta6006#rambler.ru'])
File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail
return mail.send()
File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\message.py", line 284, in send
return self.get_connection(fail_silently).send_messages([self])
File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages
new_conn_created = self.open()
File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\backends\smtp.py", line 62, in open
self.connection = self.connection_class(self.host, self.port, **connection_params)
File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 1043, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout,
File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 255, in __init__
(code, msg) = self.connect(host, port)
File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 339, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 1051, in _get_socket
new_socket = self.context.wrap_socket(new_socket,
File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\ssl.py", line 500, in wrap_socket
return self.sslsocket_class._create(
File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\ssl.py", line 1040, in _create
self.do_handshake()
File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
Exception Type: ConnectionResetError at /contact/
Exception Value: [WinError 10054] Remote host forcibly terminated existing connection
I am trying to send e-mails through my Gmail account for my Django application. I'm using below configurations in settings.py file.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST_USER = 'username#gmail.com'
EMAIL_HOST = 'smtp.gmail.com' # tried smtp-relay.gmail.com also
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
EMAIL_HOST_PASSWORD = 'Gmail password / app password'
Import statements in this regard:
from django.core.mail import send_mail, EmailMessage
from django.conf import settings
Following is in my views function:
message = EmailMessage(subject=email_subject, body=email_message, from_email=settings.EMAIL_HOST_USER, to=[email, 'username#gmail.com'])
message.send(fail_silently=False)
I have tried this also:
send_mail(email_subject, email_message , settings.EMAIL_HOST_USER, [email, 'username#gmail.com'] , fail_silently=False, )
Any help is much appreciated. Please note that I have tried:
enabling less secure apps button in Gmail
Then, I disabled less secure apps, enabled 2 factor authentication and use app passwords option of Google.
Here is the complete traceback:
Traceback (most recent call last):
File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/jatinsinghbhati/Documents/workspaces/pollsite/signup/views.py", line 40, in index
message.send(fail_silently=False)
File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/mail/message.py", line 284, in send
return self.get_connection(fail_silently).send_messages([self])
File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages
new_conn_created = self.open()
File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 62, in open
self.connection = self.connection_class(self.host, self.port, **connection_params)
File "/Users/jatinsinghbhati/.pyenv/versions/3.9.0/lib/python3.9/smtplib.py", line 253, in __init__
(code, msg) = self.connect(host, port)
File "/Users/jatinsinghbhati/.pyenv/versions/3.9.0/lib/python3.9/smtplib.py", line 339, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/Users/jatinsinghbhati/.pyenv/versions/3.9.0/lib/python3.9/smtplib.py", line 310, in _get_socket
return socket.create_connection((host, port), timeout,
File "/Users/jatinsinghbhati/.pyenv/versions/3.9.0/lib/python3.9/socket.py", line 843, in create_connection
raise err
File "/Users/jatinsinghbhati/.pyenv/versions/3.9.0/lib/python3.9/socket.py", line 831, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused
[25/Feb/2021 19:38:20] "POST /signup/ HTTP/1.1" 500 101708
It should be
EMAIL_PORT = 587
But not
EMAIL_PORT = '587'
PORT number is an integer not a string.
I'm sending emails using Django version 2.2 and have tested it on the local machine and it works. But the same code throws [Errno 97] Address family not supported by protocol exception.
I also couldn't find any solution online.
I have rechecked my code and there is nothing wrong in it.
I'm using google smtp server with app_password.
Below are Details.
settings.py file
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = "*******#gmail.com"
EMAIL_HOST_PASSWORD = "app_password"
Email Sending Function
subject = 'Account Password reset mail'
ctx = {
"user" : self.user,
"website" : settings.WEBSITE_NAME,
"site_url" : settings.WEBSITE_URL,
}
msg = render_to_string('login/forgot_password_email.html',ctx)
from_email = settings.WEBSITE_ADMIN_EMAIL
to_email = [self.cleaned_data.get('email'),]
result = send_mail(subject, '', from_email, to_email, fail_silently=False, html_message=msg)
return result
I even try to login to server through SSH and execute through the shell but returns the same error.
>>> from django.core.mail import send_mail
>>> res = send_mail('Subject here', 'Here is the message.', 'example#gmail.com', ['example#gmail.com'], fail_silently=False,)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/y6d62pncrpga/virtualenv/public_html/django/app2/3.7/lib/python3.7/site-packages/django/core/mail/__init__.py", line 60, in send_mail
return mail.send()
File "/home/y6d62pncrpga/virtualenv/public_html/django/app2/3.7/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/y6d62pncrpga/virtualenv/public_html/django/app2/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages
new_conn_created = self.open()
File "/home/y6d62pncrpga/virtualenv/public_html/django/app2/3.7/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 "/opt/alt/python37/lib64/python3.7/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 307, in _get_socket
self.source_address)
File "/opt/alt/python37/lib64/python3.7/socket.py", line 727, in create_connection
raise err
File "/opt/alt/python37/lib64/python3.7/socket.py", line 711, in create_connection
sock = socket(af, socktype, proto)
File "/opt/alt/python37/lib64/python3.7/socket.py", line 151, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
OSError: [Errno 97] Address family not supported by protocol
Thanks in Advance.
I keep getting this intermittent error when trying to send through 'smtp.gmail.com'.
Traceback (most recent call last):
File "/var/home/ptarjan/django/mysite/django/core/handlers/base.py", line 92, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/var/home/ptarjan/django/mysite/registration/views.py", line 137, in register
new_user = form.save()
File "/var/home/ptarjan/django/mysite/registration/forms.py", line 79, in save
email=self.cleaned_data['email'])
File "/var/home/ptarjan/django/mysite/django/db/transaction.py", line 240, in _commit_on_success
res = func(*args, **kw)
File "/var/home/ptarjan/django/mysite/registration/models.py", line 120, in create_inactive_user
registration_profile.send_registration_mail()
File "/var/home/ptarjan/django/mysite/registration/models.py", line 259, in send_registration_mail
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.user.email])
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 390, in send_mail
connection=connection).send()
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 266, in send
return self.get_connection(fail_silently).send_messages([self])
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 172, in send_messages
sent = self._send(message)
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 186, in _send
email_message.message().as_string())
File "/usr/lib/python2.5/smtplib.py", line 704, in sendmail
(code,resp) = self.data(msg)
File "/usr/lib/python2.5/smtplib.py", line 484, in data
(code,repl)=self.getreply()
File "/usr/lib/python2.5/smtplib.py", line 352, in getreply
line = self.file.readline()
File "/usr/lib/python2.5/smtplib.py", line 160, in readline
chr = self.sslobj.read(1)
sslerror: The read operation timed out
I'm running Django 1.1 with the django-registarion app. With these in my settings.py
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = "**SECRET**"
EMAIL_HOST_PASSWORD = "**SECRET**"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
Altho' I don't know why, I have been thro' this, and it works when you have settings variables ordered in a particular order:
EMAIL_HOST
EMAIL_PORT
EMAIL_HOST_USER
EMAIL_HOST_PASSWORD
EMAIL_USE_TLS
Looks like gmail may simply be occasionally slow to respond, so your operation times out. Perhaps you can use a try/except to catch such issues and retry a few times (maybe waiting a while between attempts). BTW, this task seems well suited to a dedicated or pooled thread which encapsulates the whole "send mail with retries" operation.