Wednesday, May 7, 2014

Sending emails

If you've noticed, on many sites, once you sign up, it sends you an automated confirmation email. This is another function your site should be able to perform. So today let's take a look at that.
Let's assume you have a Gmail account (if you don't, create one today, it's great!). We'll be using Gmail's email host (wow that rhymed).
Go to the settings.py file and add the following code anywhere in between.

EMAIL_USE_TLS = True
EMAIL_HOST = "smtp.gmail.com"
EMAIL_HOST_USER = "your_name@example.com"
EMAIL_HOST_PASSWORD = "your_password"
EMAIL_PORT = 587

The port number 587 is pretty standard. Also, it is very important to set TLS to True. We'll go into why later.
You have to enter your Gmail password there, but I assure you it is secure. Only the programmer(s) can see it. You may also create another common account and use those credentials instead.
Ok, now we'll need to write the Python code to send emails.
Open the views.py file in the appropriate app and write the following code:

At the top, import the Django's send_mail:
from django.core.mail import send_mail

Also import settings.py:
from django.conf import settings

Later, create this function:
def foo (request):
    title = "some title"
    message = "some message"
    host = settings.EMAIL_HOST_USER
    receiver = ["someone@example.com"]
    send_mail (title, message, host, receiver, fail_silently = False)
    return HttpResponse ("Mail sent successfully")

Some important things to note here:

  • You can directly write send_mail () and pass all the above values as arguments. I just wrote them separately so it's easier to understand.
  • receiver variable has to be a list or tuple, as Django supports sending emails to multiple people (a.k.a. multicasting).
  • fail_silently = False enables you to see what error was generated in case the email wasn't successfully sent. You can then use error handling to do stuff for each error. Or if the mail you're sending is not important (or an advertisement, 'cause people hate that), you can set it to True and set your mind at ease.
That's all for now! I just covered the basics here, there's a lot you can do with exceptions, responses etc. If you have questions, or are getting some error you can't identify the solution for, please feel free to ask in the comments.
Cheers!

No comments:

Post a Comment