views:

355

answers:

2

In PHP I can send an email simply by calling mail(). In Django, I need to specify SMTP backends and other things.

Is there a simpler way to send email from Django?

+3  A: 

There are several good mail-sending functions in the django.core.mail module.

For a tutorial please see Sending e-mail:

Although Python makes sending e-mail relatively easy via the smtplib library, Django provides a couple of light wrappers over it. These wrappers are provided to make sending e-mail extra quick, to make it easy to test e-mail sending during development, and to provide support for platforms that can’t use SMTP.

The simplest function that would most likely suit your purposes is the send_mail function:

send_mail(
    subject, 
    message, 
    from_email, 
    recipient_list, 
    fail_silently=False, 
    auth_user=None, 
    auth_password=None, 
    connection=None)
Andrew Hare
"Mail is sent using the SMTP host and port specified in the EMAIL_HOST and EMAIL_PORT settings." ??
valya
Well you need to specify who will be sending your email - even PHP cannot send email without _some_ sort of SMTP server configured at some location for sending email.
Andrew Hare
ok, I found the info in php.ini, but now sending emails is VERY slow.
valya
+2  A: 

In PHP you can only send mail with a simple mail() command on non-Windows systems. These will expect a local MTA like Postfix to be installed and correctly configured, as should be the case for most web servers. If you want to depend on third-party or decentralized mail service depends on how critical email is for your application. Serious dependency on speedy and reliable email transmission usually results in sending mail via SMTP to a central mail server (the "big pipe").

Still, if you want to have the same function as in PHP, try this:

import subprocess

def send_mail(from_addr, to_addr, subject, body):
  cmdline = ["/usr/sbin/sendmail", "-f"]
  cmdline.append(from_addr)
  cmdline.append(to_addr)
  mailer = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  dialog = "From: %s\nTo: %s\nSubject: %s\n\n%s\n.\n" % (from_addr, to_addr, subject, body)
  return mailer.communicate(dialog)

And use it like: send_mail ("Me <[email protected]>", "Recip Ient <[email protected]>", "Teh' Subject", "Mail body")

kread