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/
Related
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'
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.
Hi all I am new to python. I am trying to send an image to my gmail account and getting the below error can someone help me with this.
I have searched and searched and can't find an answer I have tried changing the port.
I have turned on the google less secure apps and not sure what else to do.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import os
gmail_user = "you#gmail.com"
gmail_pwd = "pass"
to = "you#gmail.com"
subject = "Report"
text = "Picture report"
attach = 'web.png'
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 465)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
Traceback (most recent call last):
File "C:\Users\scott\Desktop\PYTHON NEW\newemail.py", line 31, in <module>
mailServer = smtplib.SMTP("smtp.gmail.com", 465)
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 337, in connect
(code, msg) = self.getreply()
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 393, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
i have changed the port to 587 and got a different error
Traceback (most recent call last):
File "C:\Users\scott\Desktop\PYTHON NEW\newemail.py", line 35, in <module>
mailServer.login(gmail_user, gmail_pwd)
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 729, in login
raise last_exception
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 720, in login
initial_response_ok=initial_response_ok)
File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 641, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt4\n5.7.14 ah5smKPNBMdR8EDhHji_lOLermVkofD0XZiYZtx04cUZGJIvjm6scA9FeCEhJhB--aeW58\n5.7.14 O3uS9IVuNfqKe4HYqXgdBMbvtMSOSSMM4oGYwlvDIoXpIK0IJYKSyAfvPyPcjiF8Q_Es4n\n5.7.14 33gUceqr9ZjlNI066kXt-uTq2V39X6YUS2-ixCCKfoozS9zoQ1KJuLSWU1IhB3gTsGtB9m\n5.7.14 N-AEdgucbByvuI7zr2KG-DZwlvrWw> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 b65sm27550600wrd.26 - gsmtp')
Your code can be shortened down to just two lines:
import smtplib
mailServer = smtplib.SMTP("smtp.gmail.com", 465)
And if you get smtplib.SMTPServerDisconnected, this means that your question is not about the code. Something is blocking your network connection to port 465.
A SMTP server on port 465 is listening for encrypted TLS connections. The client is not supposed to start the encryption with STARTTLS, because TLS is active from the beginning. That SMTP command is used on port 587 where SMTP servers are listening for plaintext connections.
you can use flask_mail library for sending mail.Here is just quick review..
'
from flask_mail import Mail, Message
app.config['SECRET_KEY'] = 'your secretkey'
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'your gmail id'
app.config['MAIL_PASSWORD'] = 'and its password'
mail = Mail(app)
msg = Message(subject=subject, sender=(master().user(),
app.config['MAIL_USERNAME']), recipients=[recipients])
msg.body = "%s %s" % (body, msg.sender)
if html is not None:
msg.html = str(html)
mail.connect()
mail.send(msg)
'
***Note :- do not forget to turn off 2-step verification and also turn on Allow less secure apps from sign-in & security > device activity & security events
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