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.
Here is the settings.py file:
EMAIL_HOST = '178.67.220.242' # My current ip address
EMAIL_PORT = '587' # Port of the email host
EMAIL_HOST_USER = 'b....a1#gmail.com' # Here is my actual email
EMAIL_HOST_PASSWORD = '.....' # Here is my actual password from my email login
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
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, ['b....a1#gmail.com'])
return render(request, 'contact.html', {'form': form})
Here is the error:
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 15, in contact
send_mail(message_name, message, message_email, ['badabuska1#gmail.com'])
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 258, in __init__
raise SMTPConnectError(code, msg)
Exception Type: SMTPConnectError at /contact/
Exception Value: (421, b'Cannot connect to SMTP server 178.67.220.242 (178.67.220.242:587), connect error 10061')
Why are you putting your IP as EMAIL_HOST, this shall be the IP of the email server which by Gmail from the settings which shall be 'smtp.gmail.com'
Related
Email cannot be sent in Python.I want to send an email by using Gmail.
I wrote codes in views.py like
def mail(mail_adress, docx):
msg = MIMEMultipart()
msg["Subject"] = "TEST"
msg["From"] = settings.EMAIL_HOST_USER
msg["To"] = email
message = "TEST"
body = MIMEText(message)
msg.attach(body)
mime = {'type': 'text', 'subtype': 'docx'}
attach_file = {'name': 'test.docx', 'path': '/Users/test.docx'}
attachment = MIMEBase(mime['type'], mime['subtype'])
file = open(attach_file['path'], 'rb')
attachment.set_payload(file.read())
file.close()
encoders.encode_base64(attachment)
msg.attach(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=attach_file['name'])
return msg
def send(from_addr, to_addrs, msg):
smtp = smtplib.SMTP()
smtp.connect()
from_addr = 'xxxx#gmail.com'
from_addr_name = "test"
to_addr= "yyyyy#gmail.com"
subject = u"test"
message = "test"
body = MIMEText(message)
mime = {'type': 'text', 'subtype': 'docx'}
attach_file = {'name': 'test.docx', 'path': '/Users/test.docx'}
msg = mail(from_addr, from_addr_name, to_addr, subject, body, mime, attach_file)
smtp.sendmail(from_addr, to_addrs, msg)
smtp.close()
send()
in settings.py
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'xxxx#gmail.com'
EMAIL_HOST_PASSWORD = 'xxxxxxxxx'
EMAIL_USE_TLS = True
When I run the codes,
[Errno 61] Connection refused error happens.Traceback says
Traceback (most recent call last):
File "/Users/xxxx/anaconda3/envs/py36/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/Users/xxxx/anaconda3/envs/py36/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/xxxx/anaconda3/envs/py36/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/xxxx/Downloads/legal_doc_mail/common/views.py", line 400, in make_document
send()
File "/Users/xxxx/Downloads/legal_doc_mail/common/views.py", line 454, in send
smtp.connect()
File "/Users/xxxx/anaconda3/envs/py36/lib/python3.6/smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/Users/xxxx/anaconda3/envs/py36/lib/python3.6/smtplib.py", line 307, in _get_socket
self.source_address)
File "/Users/xxxx/anaconda3/envs/py36/lib/python3.6/socket.py", line 724, in create_connection
raise err
File "/Users/xxxx/anaconda3/envs/py36/lib/python3.6/socket.py", line 713, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused
I really cannot understand why such an error happens.What is wrong in my codes?How should I fix this?
Settings.py
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'xxxx#gmail.com'
EMAIL_HOST_PASSWORD = 'xxxxxxxxx'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
Go to your Google Account settings, find Security -> Account permissions -> Access for less secure apps, enable let less secure apps sign in option.
https://support.google.com/accounts/answer/6010255
[Errorno 61] is due to connection refused by server. See if this could help.
If someone had this issue, I will be sincerely thankful for your help.
I'm having this error sending local email with hotmail:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/huey/consumer.py", line 169, in process_task
task_value = self.huey.execute(task)
File "/usr/local/lib/python3.6/site-packages/huey/api.py", line 357, in execute
result = task.execute()
File "/usr/local/lib/python3.6/site-packages/huey/api.py", line 842, in execute
return func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/huey/contrib/djhuey/__init__.py", line 108, in inner
return fn(*args, **kwargs)
File "/code/app/tasks.py", line 89, in send_email
email_message.send()
File "/usr/local/lib/python3.6/site-packages/django/core/mail/message.py", line 348, in send
return self.get_connection(fail_silently).send_messages([self])
File "/usr/local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages
sent = self._send(message)
File "/usr/local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 127, in _send
self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
File "/usr/local/lib/python3.6/smtplib.py", line 888, in sendmail
raise SMTPDataError(code, resp)
smtplib.SMTPDataError: (432, b'4.3.2 STOREDRV.ClientSubmit; sender thread limit exceeded [Hostname=DM5PR19MB1050.namprd19.prod.outlook.com]')
ERROR process_task Unhandled exception in worker thread
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/huey/consumer.py", line 169, in process_task
task_value = self.huey.execute(task)
File "/usr/local/lib/python3.6/site-packages/huey/api.py", line 357, in execute
result = task.execute()
File "/usr/local/lib/python3.6/site-packages/huey/api.py", line 842, in execute
return func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/huey/contrib/djhuey/__init__.py", line 108, in inner
return fn(*args, **kwargs)
File "/code/app/tasks.py", line 89, in send_email
email_message.send()
File "/usr/local/lib/python3.6/site-packages/django/core/mail/message.py", line 348, in send
return self.get_connection(fail_silently).send_messages([self])
File "/usr/local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages
sent = self._send(message)
File "/usr/local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 127, in _send
self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
File "/usr/local/lib/python3.6/smtplib.py", line 888, in sendmail
raise SMTPDataError(code, resp)
smtplib.SMTPDataError: (554, b'5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied; Failed to process message due to a permanent exception with message Cannot submit message. 16.55847:050B0000, 17.43559:0000000094000000000000000000000000000000, 20.52176:140F248214004010F1030000, 20.50032:140F248285174010F1030000, 0.35180:0A00B681, 255.23226:F1030000, 255.27962:0A000000, 255.27962:0E000000, 255.31418:0A00F784, 16.55847:EC000000, 17.43559:0000000068010000000000000000000000000000, 20.52176:140F2482140000100A00F736, 20.50032:140F24828517001181170000, 0.35180:00000000, 255.23226:00000000, 255.27962:0A000000, 255.27962:32000000, 255.17082:DC040000, 0.27745:140F2482, 4.21921:DC040000, 255.27962:FA000000, 255.1494:A4010000, 0.37692:05000780, 0.37948:00000600, 5.33852:00000000534D545000000000, 4.56248:DC040000, 7.40748:010000000000010B32303A44, 7.57132:00000000000000003A346638, 1.63016:32000000, 4.39640:DC040000, 8.45434:0000060075AF4541000000000000000032000000, 5.10786:0000000031352E32302E303534382E3032303A444D35505231394D42313035303A34663832663161652D373465382D343830632D623637302D34326236313339313335383200401005000780, 255.1750:0A00FC83, 255.31418:41010000, 0.22753:0A001E85, 255.21817:DC040000, 4.60547:DC040000, 0.21966:4B010000, 4.30158:DC040000 [Hostname=DM5PR19MB1050.namprd19.prod.outlook.com]')
That is my configuration on settings.py
I try changing the port to 587, try with gmail account but doesn't work
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp-mail.outlook.com'
EMAIL_HOST_USER = 'myemail#hotmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 25
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
It's probably missing "Email From" variable either in settings.py or your view.
Try this:
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.live.com'
EMAIL_HOST_USER = 'youremail#hotmail.com'
DEFAULT_FROM_EMAIL = 'youremail#hotmail.com'
EMAIL_FROM = 'youremail#hotmail.com'
EMAIL_HOST_PASSWORD = 'yourpassword'
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL is used in stock Django views, but if you have your own custom one, then you can import those variables as well:
from django.conf import settings
send_mail(
mail_subject,
message,
settings.EMAIL_FROM,
[to_email],
fail_silently=False,
)
This can be solved very easily by adding the following line in settings.py:
EMAIL_HOST_USER = "support#urmail.com"
DEFAULT_FROM_EMAIL = "support#urmail.com"
Make sure that both EMAIL_HOST_USER and DEFAULT_FROM_EMAIL is same email Id.
send_mail also will work perfectly but there is no facility to add attachment in that option.
I'm using the standard Django/SendGrid setup for sending emails. Here's the relevant fields in my settings.py:
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'myusername'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 465
EMAIL_USE_SSL = True
DEFAULT_FROM_EMAIL = 'admin#mysite.com'
I'm testing sending emails in my shell by executing:
send_mail('test','test','email#email.com',['to#email.com'])
however, it returns this error Traceback:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/mail/__init__.py", line 62, in send_mail
return mail.send()
File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/mail/message.py", line 348, in send
return self.get_connection(fail_silently).send_messages([self])
File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 104, in send_messages
new_conn_created = self.open()
File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 71, in open
self.connection.login(force_str(self.username), force_str(self.password))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 720, in login
initial_response_ok=initial_response_ok)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 630, in auth
(code, resp) = self.docmd("AUTH", mechanism + " " + response)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 420, in docmd
return self.getreply()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 393, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
Any idea why I'm getting this error?
PS: This is my local development server
Updated 2021
Sendgrid now requires using API Key instead of username/password:
Two-Factor Authentication is required as of Q4 2020, and all Twilio
SendGrid API endpoints will reject new API requests and SMTP
configurations made with a username and password via Basic
Authentication.
So you'll need to create an API Key with at least Mail Send > Full Access permissions, then tweak your Django configs like this:
EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey'
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
Sample code:
settings.py
SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey'
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
EMAIL_PORT = 587
EMAIL_USE_TLS = True
utils.py
from django.core.mail import send_mail
send_mail('Subject here', 'Here is the message.', 'from#example.com', ['to#example.com'], fail_silently=False)
EMAIL_PORT = 465
EMAIL_USE_SSL = True
change this
EMAIL_PORT = 587
EMAIL_USE_TLS = True
and you can check this link
https://sendgrid.com/docs/for-developers/sending-email/django/
On the vps where I host a django website, I have set up a postfix mailserver to be used by django for email. The mailserver works. Using mutt on the vps command line, I can send and receive mail to/from other accounts like gmail etc.
Still, I am having trouble using postfix to send mail from django.
I followed the advice in https://stackoverflow.com/a/28143166/1009979, with settings...
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
When I try
>>> from django.core.mail import send_mail
>>> send_mail('Subject here', 'Here is the message.', 'from#example.com', ['andrews.markw#gmail.com'])
I get
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/andrews/development/wilhelm-development/local/lib/python2.7/site-packages/django/core/mail/__init__.py", line 62, in send_mail
return mail.send()
File "/home/andrews/development/wilhelm-development/local/lib/python2.7/site-packages/django/core/mail/message.py", line 303, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/andrews/development/wilhelm-development/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 107, in send_messages
sent = self._send(message)
File "/home/andrews/development/wilhelm-development/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 123, in _send
self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
File "/usr/lib/python2.7/smtplib.py", line 733, in sendmail
raise SMTPRecipientsRefused(senderrs)
SMTPRecipientsRefused: {u'andrews.markw#gmail.com': (550, '5.7.1 <vps7718.webhosting.uk.com>: Helo command rejected: Host not found')}
When I google for advice about SMTPRecipientsRefused: or Helo command rejected: Host not found, no obvious solutions to my problems arise.
Is there something wrong with the settings?
I should mention that I have no general problem problem with django email. For example, I can send gmail emails from django (following settings and procedure described here https://stackoverflow.com/a/23402208/1009979).
Make sure you have permit_mynetworks in smtpd_helo_restrictions and smtpd_recipient_restrictions in /etc/postfix/main.cf
I'm using django-registration for handling of users registration. I tried to signup in order to test it, after testing it, I got this error
SMTPConnectError at /accounts/register/
Being trying to find a solution yet no success!
Full Traceback
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\registration\views.py" in register
187. new_user = backend.register(request, **form.cleaned_data)
File "C:\Python27\lib\site-packages\registration\backends\default\__init__.py" in register
79. password, site) File "C:\Python27\lib\site-packages\django\db\transaction.py" in inner
209. return func(*args, **kwargs) File "C:\Python27\lib\site- packages\registration\models.py" in create_inactive_user
85. registration_profile.send_activation_email(site)
File "C:\Python27\lib\site-packages\registration\models.py" in send_activation_email
264. self.user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
File "C:\Python27\lib\site-packages\django\contrib\auth\models.py" in email_user
374. send_mail(subject, message, from_email, [self.email])
File "C:\Python27\lib\site-packages\django\core\mail\__init__.py" in send_mail
61. connection=connection).send()
File "C:\Python27\lib\site-packages\django\core\mail\message.py" in send
248. return self.get_connection(fail_silently).send_messages([self])
File "C:\Python27\lib\site-packages\django\core\mail\backends\smtp.py" in send_messages
85. new_conn_created = self.open()
File "C:\Python27\lib\site-packages\django\core\mail\backends\smtp.py" in open
48. local_hostname=DNS_NAME.get_fqdn())
File "C:\Python27\lib\smtplib.py" in __init__
251. raise SMTPConnectError(code, msg)
Exception Type: SMTPConnectError at /accounts/register/
Exception Value: (451, 'Request action aborted on MFE proxy, SMTP server is not available.')
In Settings.py
EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS=True
EMAIL_HOST='smtp.test.com'
EMAIL_HOST_USER='test#test.com'
EMAIL_HOST_PASSWORD='f88lm'
EMAIL_PORT=587
DEFAULT_FROM_EMAIL = 'test#test.com'
SERVER_EMAIL = 'test#test.com'
Of course there is an error, you have given details for an SMPT server that doesn't exist so Django can't connect to it when trying to send email. While developing, either use the dummy email backend:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
or run a test email server locally.
The problem is from my domain email hosting provider. Thanks!