Django; sending email from my own postfix mail server - python

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

Related

(421, b'Cannot connect to SMTP server, connect error 10061')

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'

Limit on email sending using gmail [duplicate]

I wrote a simple script to send an email via the Gmail SMTP server. Here the code:
import smtplib
msg = 'Hello World!'
server = smtplib.SMTP('smtp.gmail.com', 587) #port 465 or 587
server.ehlo()
server.starttls()
server.ehlo()
server.login('username#googlemail.com','password')
server.sendmail('username#googlemail.com','username#googlemail.com', msg)
server.close()
Sometimes it works and sometimes I get an error. What is the reason for it? I have configured Gmail for accepting less secure apps. If the error occurs I get the following message:
Traceback (most recent call last):
File "email.py", line 31, in <module>
server.login('username#googlemail.com','password')
File "/usr/lib/python3.5/smtplib.py", line 729, in login
raise last_exception
File "/usr/lib/python3.5/smtplib.py", line 720, in login
initial_response_ok=initial_response_ok)
File "/usr/lib/python3.5/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=AKgnsbvQ\n5.7.14 DBMYWMukfjghdjfkghfjkhjkfhgjkdhgdfjkghekjghekjgndjkSm5lAOfEpP2Nt\n5.7.14 QihtNp5izjfghjjkjhgbhjbGHJVHJVjhvhjbhjbhjDZwhJFV-FiyvI-OGW\n5.7.14 jcpmHcQAcOR8e8G0zOfdugjhfdjd-sdfiugdsjfdsrthdfewrzjhg-shgv2HxmgWpZg3Z\n5.7.14 4G1ENiAlgiEnrkXyRbTG3frjZZdPg> 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 g40sm24698383wrg.19 - gsmtp')
I couldn't find any help on the internet. Many thanks in advance for every advice.
The answer recommends enabling access for less secure apps first. If that does not work you could try visiting the link, which is supplied on that page: https://www.google.com/accounts/DisplayUnlockCaptcha
This may enable access.

Django email not working - smtplib.SMTPServerDisconnected: Connection unexpectedly closed

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/

Python smtplib: Gmail works, but only "sometimes"

I wrote a simple script to send an email via the Gmail SMTP server. Here the code:
import smtplib
msg = 'Hello World!'
server = smtplib.SMTP('smtp.gmail.com', 587) #port 465 or 587
server.ehlo()
server.starttls()
server.ehlo()
server.login('username#googlemail.com','password')
server.sendmail('username#googlemail.com','username#googlemail.com', msg)
server.close()
Sometimes it works and sometimes I get an error. What is the reason for it? I have configured Gmail for accepting less secure apps. If the error occurs I get the following message:
Traceback (most recent call last):
File "email.py", line 31, in <module>
server.login('username#googlemail.com','password')
File "/usr/lib/python3.5/smtplib.py", line 729, in login
raise last_exception
File "/usr/lib/python3.5/smtplib.py", line 720, in login
initial_response_ok=initial_response_ok)
File "/usr/lib/python3.5/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=AKgnsbvQ\n5.7.14 DBMYWMukfjghdjfkghfjkhjkfhgjkdhgdfjkghekjghekjgndjkSm5lAOfEpP2Nt\n5.7.14 QihtNp5izjfghjjkjhgbhjbGHJVHJVjhvhjbhjbhjDZwhJFV-FiyvI-OGW\n5.7.14 jcpmHcQAcOR8e8G0zOfdugjhfdjd-sdfiugdsjfdsrthdfewrzjhg-shgv2HxmgWpZg3Z\n5.7.14 4G1ENiAlgiEnrkXyRbTG3frjZZdPg> 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 g40sm24698383wrg.19 - gsmtp')
I couldn't find any help on the internet. Many thanks in advance for every advice.
The answer recommends enabling access for less secure apps first. If that does not work you could try visiting the link, which is supplied on that page: https://www.google.com/accounts/DisplayUnlockCaptcha
This may enable access.

Send email from server python

I am trying to send an email form my server with python, I asked my server provider what port to use for this and they said "choose SMTP Ports 465 (Secure SSL/TLS outgoing server) , 25 ( Non-SSL outgoing server)." Not sure what this exactly means but currently I am using 25, here is my code
#! /usr/bin/python
import smtplib
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 25)
#Next, log in to the server
server.login("youremailusername", "password")
#Send the mail
msg = "\nHello!" # The /n separates the message from the headers
server.sendmail("you#gmail.com", "target#example.com", msg)
I filled in my username (which is my email address right) and password,a dn the target but it is not working, when I try to navigate to the url where my py script is, it just doesn't load. I have an internet connection cause I am loving other things, and go to other pages on my server. I have also tried running with cron jobs but that also doesn't work.
The permissions on the script are 0755, is there a problem with the script?
When i ran with cron jobs here is the traceback
Traceback (most recent call last):
File "/home/spencerf/public_html/cgi-bin/send_email.py", line 6, in <module>
server = smtplib.SMTP('smtp.gmail.com', 25)
File "/usr/lib64/python2.6/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib64/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib64/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib64/python2.6/socket.py", line 567, in create_connection
raise error, msg
socket.error: [Errno 101] Network is unreachable
Thanks for the help in advance.
EDIT
here is updated error log with the port at 587
Traceback (most recent call last):
File "/home/spencerf/public_html/cgi-bin/send_email.py", line 7, in <module>
server = smtplib.SMTP('smtp.gmail.com', 587)
File "/usr/lib64/python2.6/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib64/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib64/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib64/python2.6/socket.py", line 567, in create_connection
raise error, msg
socket.error: [Errno 101] Network is unreachable
EDIT 2
When I had server = smtplib.SMTP('telnet smtp.gmail.com', 587)
I got this error
Traceback (most recent call last):
File "/home/spencerf/public_html/cgi-bin/send_email.py", line 8, in <module>
server = smtplib.SMTP('telnet smtp.gmail.com', 587)
File "/usr/lib64/python2.6/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib64/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib64/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib64/python2.6/socket.py", line 553, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known
BUG:
First of all you are using gmail server not your company server to send mail .For gmail server the output port is 587
The code:
Due to security issues gmail blocks accessing mail via code or program
But still you can use gmail to send mail via code if you do the following things
What i have done in code :
1.Added a error object to get the error message
import smtplib
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
#Next, log in to the server
server.login("youremailusername", "password")
#Send the mail
msg = "\nHello!" # The /n separates the message from the headers
server.sendmail("you#gmail.com", "target#example.com", msg)
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
Updated
import smtplib
try:
content = 'test'
mail = smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login("ABC#gmail.com", "password")
mail.sendmail("ABC#gmail.com", "recivermailaddress", content)
mail.quit
print "Successfully sent email"
except smtplib.SMTPException,error:
print str(error)
In python, please download yagmail (disclaimer: I'm the developer):
pip install yagmail
It is then simply a matter of:
import yagmail
yag = yagmail.SMTP("you#gmail.com", "password")
yag.send("target#example.com", 'This is the subject', 'Hello!')
I guess it mostly just has to do with the fact that you gave a wrong port (smtp.gmail.com is not at 25).
On the github you can also see a common list of errors.

Categories

Resources