Sending email via django on windows - python

Ugh, I have tried as many ways is I have been able to find online thus far, but to no avail. My primary objective is to send email from a django based web application on a private LAN. I don't care how it happens...smtp or win32com and outlook...anything, as long is it works.
Using django default settings and this code in a django shell:
from django.core.mail import send_mail
send_mail('subject','message','myemail#email.com',['myemail#email.com'])
I get this error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27_32\lib\site-packages\django\core\mail\__init__.py", line 50, in send_mail
connection=connection).send()
File "C:\Python27_32\lib\site-packages\django\core\mail\message.py", line 274, in send
return self.get_connection(fail_silently).send_messages([self])
File "C:\Python27_32\lib\site-packages\django\core\mail\backends\smtp.py", line 87, in send_messages
new_conn_created = self.open()
File "C:\Python27_32\lib\site-packages\django\core\mail\backends\smtp.py", line 48, in open
local_hostname=DNS_NAME.get_fqdn())
File "C:\Python27_32\lib\smtplib.py", line 250, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python27_32\lib\smtplib.py", line 311, in connect
(code, msg) = self.getreply()
File "C:\Python27_32\lib\smtplib.py", line 359, in getreply
+ str(e))
SMTPServerDisconected: Connection unexpectedly closed: [Errno 10057] A request to send or
receive data was disallowed because the socket is not connected and (when sending on a
datagram socket using a sendto call) no address was supplied
After digging into the code, I inserted a print statement in smtplib showing the address as ('localhost', 25). So I don't know why it says no address was supplied. That's when I discovered django-smtp-ssl.py and after installing added the following to my settings:
EMAIL_USE_TLS = True #also tried 1
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_HOST_USER = 'myemail#email.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 465
Then executing the same code, I now get:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27_32\lib\site-packages\django\core\mail\__init__.py", line 50, in send_mail
connection=connection).send()
File "C:\Python27_32\lib\site-packages\django\core\mail\message.py", line 274, in send
return self.get_connection(fail_silently).send_messages([self])
File "C:\Python27_32\lib\site-packages\django\core\mail\backends\smtp.py", line 87, in send_messages
new_conn_created = self.open()
File "C:\Python27_32\lib\site-packages\django_smtp_ssl.py", line 12, in open
local_hostname=DNS_NAME.getfqdn())
File "C:\Python27_32\lib\smtplib.py", line 777, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python27_32\lib\smtplib.py", line 250, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python27_32\lib\smtplib.py", line 311, in connect
(code, msg) = self.getreply()
File "C:\Python27_32\lib\smtplib.py", line 355, in getreply
line = self.file.readline()
File "C:\Python27_32\lib\smtplib.py", line 186, in readline
chr = self.sslobj.read(1)
File "C:\Python27_32\lib\ssl.py", line 160, in read
return self._sslobj.read(len)
AttributeError: 'NoneType' object has no attribute 'read'
I have additionally tried sending mail via Outlook and win32com in a production environment using Apache. I have received a couple different exceptions trying this, such as: 'Server execution failed and 'Call was rejected by callee'. Although it works in a django shell (of course).
Has anyone seen these any of these errors and found resolution? Thank you for any help!

And it's the workaround, nothing short of shoddy, but it'll get the job done until a better solution presents itself.
First I created a custom command that can be called from manage.py as it is not executed from the Apache server (which further tells me that the system does not recognize Apache as a valid user for automatic email generation, certainly there's a way to tell the system "it's okay").
Following that, I created a task in Windows Task Scheduler to run every 30 min (which will suffice for the objective). Action:
Start a program C:\python27_32\python.exe C:\www\myproject\manage.py send_email
myapp/management/commands/send_email.py
from django.core.management.base import BaseCommand
from myapp.util.gen_email import AutoEmail #custom code to generate email via win32com
from myapp.models import MyModel
class Command(BaseCommand):
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
items = MyModel.objects.filter(status__in=['status_a','status_b'])
if items:
self.send_proc_email()
def send_proc_email(self):
subject = 'There are new items to process'
to = 'someemail#email.com'
message = ''
email = AutoEmail(subject, message, to)
def handle(self, *args, **kwargs):
pass
Far from optimal, I know, but hey if it works...

Related

Asynchronious email sending in Django

I'm trying to figure out how to send email asynchroniously so User don't have to wait until email is sent.
I've installer celery and django-celery-email and added django-celery-email into my settings.py - djcelery_email.
I've also changed database backend:
EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend'
Now I've tried to do an action which sends email but it freezes and no email has been sent.
Do you know what to do?
Here is a traceback from cmd:
Internal Server Error: /ajax/reservation/confirm/
Traceback (most recent call last):
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\django\core\handlers\base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\dolava_app\views.py", line 68, in reservation_confirm
reservation.save()
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\dolava_app\models.py", line 150, in save
notifications.AdminNotifications.new_pair(self, paired_reservation)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\dolava_app\notifications.py", line 79, in new_pair
send_message_to_admin(subject,message)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\dolava_app\notifications.py", line 8, in send_message_to_admin
mail.send()
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\django\core\mail\message.py", line 292, in send
return self.get_connection(fail_silently).send_messages([self])
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\djcelery_email\backends.py", line 17, in send_messages
result_tasks.append(send_emails.delay(chunk, self.init_kwargs))
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\celery\app\task.py", line 453, in delay
return self.apply_async(args, kwargs)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\celery\app\task.py", line 565, in apply_async
**dict(self._get_exec_options(), **options)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\celery\app\base.py", line 354, in send_task
reply_to=reply_to or self.oid, **options
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\celery\app\amqp.py", line 310, in publish_task
**kwargs
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\messaging.py", line 172, in publish
routing_key, mandatory, immediate, exchange, declare)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\connection.py", line 457, in _ensured
interval_max)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\connection.py", line 369, in ensure_connection
interval_start, interval_step, interval_max, callback)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\utils\__init__.py", line 246, in retry_over_time
return fun(*args, **kwargs)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\connection.py", line 237, in connect
return self.connection
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\connection.py", line 742, in connection
self._connection = self._establish_connection()
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\connection.py", line 697, in _establish_connection
conn = self.transport.establish_connection()
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\transport\pyamqp.py", line 116, in establish_connection
conn = self.Connection(**opts)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\amqp\connection.py", line 165, in __init__
self.transport = self.Transport(host, connect_timeout, ssl)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\amqp\connection.py", line 186, in Transport
return create_transport(host, connect_timeout, ssl)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\amqp\transport.py", line 299, in create_transport
return TCPTransport(host, connect_timeout)
File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\amqp\transport.py", line 95, in __init__
raise socket.error(last_err)
error: [Errno 10061] No connection could be made because the target machine actively refused it
Problem
From https://github.com/pmclanahan/django-celery-email
By default django-celery-email will use Django's builtin SMTP email
backend for the actual sending of the mail.
This means you need to run an SMTP server locally to accept the email. That is why you are getting a socket error - cause you don't have any SMTP server set to receive the email.
Possible Solutions - Local Development
A. Start an SMTP server and use your own client
Option 1
Run a combined SMTP server and client.
Mailcatcher is great for this.
It even comes with django setup instructions!
Set it up then fire it up with:
$ mailcatcher -fv
Note: mailcatcher requires gem (ruby package manager) to install.
So you will have to install that first.
Its probably worth the effort, as mailcatcher works quite nicely and
gives you html and text representations of the email in a browser tab.
For docker users you can get a mailcatcher docker image
Option 2
Run your own SMTP server and a separate mail client.
e.g. Use a simple python SMTP server
From the command line
python -m smtpd -n -c DebuggingServer localhost:1025
in your django settings:
EMAIL_HOST = 'localhost'
EMAIL_HOST_USER = None
EMAIL_HOST_PASSWORD = None
EMAIL_PORT = 1025
EMAIL_USE_TLS = False
Then you will need to setup a client to get those emails.
B. Don't use SMTP as a backend in your settings
Instead print to the console:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Problem with this is ugly formatting.
HTML will appear as text which makes the email very hard to read. You can output this to a file by manually copying and pasting it into a .html file and opening it in a browser, but that will get boring very fast.
Solution - Continuous Integration Server
Use this for making email accessible to the django test client, so you can check that emails got sent, check the content of email programatically etc.
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
Solution - Production Server
You will need to use a SMTP server again.
Either you can run your own or use Sendgrid, Mailgun, Mandrill or something similar.

py2neo (Neo4j) : py2neo.packages.httpstream.http.SocketError: Operation not permitted

I am running Neo4j 2.2.1 in ubuntu Amazon EC2 instance. When I am trying to connect through python using py2neo-2.0.7, I am getting following error :
py2neo.packages.httpstream.http.SocketError: Operation not permitted
I am able to access the web-interface through http://52.10.**.***:7474/browser/
CODE :-
from py2neo import Graph, watch, Node, Relationship
url_graph_conn = "https://neo4j:password#52.10.**.***:7474/db/data/"
print url_graph_conn
my_conn = Graph(url_graph_conn)
babynames = my_conn.find("BabyName")
for babyname in babynames:
print 2
Error message :-
https://neo4j:password#52.10.**.***:7474/db/data/
Traceback (most recent call last):
File "C:\Users\rharoon002\eclipse_workspace\peace\peace\core\graphconnection.py", line 39, in <module>
for babyname in babynames:
File "C:\Python27\lib\site-packages\py2neo\core.py", line 770, in find
response = self.cypher.post(statement, parameters)
File "C:\Python27\lib\site-packages\py2neo\core.py", line 667, in cypher
metadata = self.resource.metadata
File "C:\Python27\lib\site-packages\py2neo\core.py", line 213, in metadata
self.get()
File "C:\Python27\lib\site-packages\py2neo\core.py", line 258, in get
response = self.__base.get(headers=headers, redirect_limit=redirect_limit, **kwargs)
File "C:\Python27\lib\site-packages\py2neo\packages\httpstream\http.py", line 966, in get
return self.__get_or_head("GET", if_modified_since, headers, redirect_limit, **kwargs)
File "C:\Python27\lib\site-packages\py2neo\packages\httpstream\http.py", line 943, in __get_or_head
return rq.submit(redirect_limit=redirect_limit, **kwargs)
File "C:\Python27\lib\site-packages\py2neo\packages\httpstream\http.py", line 433, in submit
http, rs = submit(self.method, uri, self.body, self.headers)
File "C:\Python27\lib\site-packages\py2neo\packages\httpstream\http.py", line 362, in submit
raise SocketError(code, description, host_port=uri.host_port)
py2neo.packages.httpstream.http.SocketError: Operation not permitted
You are trying to access neo4j via https on the standard port for http (7474):
url_graph_conn = "https://neo4j:password#52.10.**.***:7474/db/data/"
The standard port for a https connection is 7473. Try:
url_graph_conn = "https://neo4j:password#52.10.**.***:7473/db/data/"
And make sure you can access the web interface via https:
https://52.10.**.***:7473/browser/
You can change/see the port settings in your neo4j-server.properties file.

How to send simple email using Python

Before you mark this as a duplicate; I've read the other threads as well. I'm trying to send an email as simple as using the mail() function in php. I simply tried the example from the official python docs. But when I try to connect with the localhost on my linux machine I get:
>>> import smtplib
>>> smtplib.SMTP('localhost')
Traceback (most recent call last):
File "<input>", line 1, in <module>
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 311, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 286, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
error: [Errno 111] Connection refused
I thought this example didn't need an email server to run (just like the php mail() function doesn't need an email-server to run).
Any ideas what I might be doing wrong or how I can get this to send an email? All tips are welcome!
The php mail() function does need a relay to send messages. It defaults to sendmail on Linux machines.
On Windows you have to give it the address of a SMTP server.
In order for any program to send email, you need to connect to a SMTP server. There is no running around that.

Python application using office365 exchange server timing out

I have a Python program that collects about 11K entries from a CORBA database, then uses those entries to parse through about 1,0000 Mb of text files. This entire process normally takes 5-7 minutes. I log into the Exchange365 server before this starts (so that any unusual events can be emailed to the administrator) and then try to email the results to the 'normal' recipients. That last email is failing and the root cause seems to be that I am getting logged off of the Exchange server.
Adding a 'dummy' email about half way through the processing seems to eliminate the timeout, but I'd like to find a more programatic way to accomplish this. Following is a code snippet where I enable the email:
import smtp
import time
pretty_localtime = time.asctime()
smtpserver = smtplib.SMTP("smtp.office365.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
#
try:
smtpserver.login(office365_user,office365_pwd)
except:
msg = ("%s --- FATAL ERROR: Couldn't log into SMTP server.")%pretty_localtime
log_file.write("%s \n"%msg)
print msg
sys.exit()
Has anyone worked through this problem?
***edit** Python error added:
Traceback (most recent call last):
File "piu_billing.py", line 739, in <module>
log_file.write(email_msg)
File "piu_billing.py", line 102, in send_mail
smtpserver.sendmail(office365_user,to,themsg)
File "C:\Python27\lib\smtplib.py", line 719, in sendmail
(code, resp) = self.mail(from_addr, esmtp_opts)
File "C:\Python27\lib\smtplib.py", line 471, in mail
self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender), optionlist))
File "C:\Python27\lib\smtplib.py", line 334, in putcmd
self.send(str)
File "C:\Python27\lib\smtplib.py", line 324, in send
raise SMTPServerDisconnected('Server not connected')
smtplib.SMTPServerDisconnected: Server not connected

What's causing this imaplib error in Python script for AppEngine?

This script:
import imaplib
user = "dave.trindall#gmail.com"
pwd = "***"
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select("Inbox") # here you a can choose a mail box like INBOX instead
m.search("NEW")
makes this error for me:
Traceback (most recent call last):
File "c:\Program Files\Google\google_appengine\google\appengine\ext\webapp\_webapp25.py", line 701, in __call__
handler.get(*groups)
File "c:\Users\Dave\git_stuff\Touch Base\Touch Base\main.py", line 30, in get
m = imaplib.IMAP4_SSL("imap.gmail.com")
File "c:\Python26\lib\imaplib.py", line 1138, in __init__
IMAP4.__init__(self, host, port)
File "c:\Python26\lib\imaplib.py", line 163, in __init__
self.open(host, port)
File "c:\Python26\lib\imaplib.py", line 1149, in open
self.sock = socket.create_connection((host, port))
AttributeError: 'module' object has no attribute 'create_connection'
Why?
This fails because App-Engine disallows opening sockets in your application. See the 'Pure Python' section in http://code.google.com/appengine/docs/python/runtime.html, also discussion at http://groups.google.com/group/google-appengine/browse_thread/thread/4a8764d266ec17af
Note that while you can't make raw socket connections from App Engine, you can send mail using the Mail API and you can read a Gmail inbox using the Gmail Inbox Feed.

Categories

Resources