Send mails with Django

Here a simple script to send a mail through Django, a very fast web framework written in Python:

sendmail.py:

from django.core.mail import send_mail

send_mail(‘subject’, ‘text by Luke’, ‘jedim@vige.it’, [‘lsflashboss62@gmail.com’], fail_silently=False)

settings.py:

# Host for sending e-mail.

EMAIL_HOST = ‘smtp.gmail.com’

# Port for sending e-mail.

EMAIL_PORT = 25

# Optional SMTP authentication information for EMAIL_HOST.

EMAIL_HOST_USER = ‘lsflashboss62@gmail.com’

EMAIL_HOST_PASSWORD = ‘passwwooooooorddddd’

EMAIL_USE_TLS = True

If we want send attachments we need to write a new send_mail function. Here an example:

from django.core.mail import get_connection, EmailMessage

import tempfile

def send_mail(subject, message, from_email, recipient_list,

fail_silently=False, auth_user=None, auth_password=None,

connection=None):

connection = connection or get_connection(username=auth_user,

password=auth_password,

fail_silently=fail_silently)

mail = EmailMessage(subject, message, from_email, recipient_list,

connection=connection)

attach = tempfile.NamedTemporaryFile(delete=True)

mail.attach(attach.name, attach.read(), attach.content_type)

return mail.send()

To create a mail crawler, it’s very simple:

download Django cron from svn:

svn checkout http://django-cron.googlecode.com/svn/trunk/ django-cron-read-only

and install it in the python path. More details are in the README.txt of the django cron project.

In the INSTALLED_APPS of your settings.py add the django_cron project:

INSTALLED_APPS = (

‘django_cron’,

)

Add the rows in the urls.py:

import django_cron

django_cron.autodiscover()

Add a cron.py file in the same path of your settings.py:

from django_cron import cronScheduler, Job

from Myproject.polls import send_mail

class CheckMail(Job):

# run every 300 seconds (5 minutes)

run_every = 300

def job(self):

# This will be executed every 5 minutes

send_mail(‘ciao’, ‘ciao da Luke’, ‘jedim@vige.it’, [‘lsflashboss62@gmail.com’], fail_silently=False)

cronScheduler.register(CheckMail)

This cron starts at the first request of the webapp and it will send emails each 300 ms