Codementor Events

How to Send Mail in Python with Web2py

Published Dec 20, 2016Last updated Jan 18, 2017
How to Send Mail in Python with Web2py

With a little training or basic knowledge in programming, it is quite possible to develop a full web application with the help of full-stack frameworks like Web2py.

What you will learn:

In this tutorial, we will learn how to:

  • Implement Web2py’s send.mail() to set up or configure emails and finally show how to send emails to users.

Prior to that, we will also cover:

  • The core of Web2py
  • Where to get the binary distribution for a specific operating system and how to install it
  • How to start the administrative interface via the GUI
  • Configure the mail settings via the mailer class and send mail

Web2py like other frameworks written in python have a steep learning curve but it is quite flexible than the others.

Introduction to Web2py:

Web2py is a full stack framework written in Python and programmable in Python. Web2py was created by Massimo Di Pierro in 2008. Since its inception, diverse projects such http://www.rockiger.com, http://tenthrow.com  and others have benefitted from Web2py. We can go on and on forever, but let’s briefly introduce Web2py to the world.

Unlike other traditional programming languages, Web2py follows the model-view-controller concept.

Below is the representation of the MVC concept :

  • Model – db.py The model includes the logic of the application or the application logic. In the model, there are objects which retrieves and stores objects in the database.
  • Controller – default.py Controller handles user interaction, send data input to the specific model and may be able to read data from the view.
  • View – default/contact.html The view helps with data representation. The data is fetched from the model and then rendered to the end users.

In addition, it supports various protocols such as RSS, CSV, HTML, JSON, RTF, and XML. For instance, let’s say a user requests for a page in XML, Web2py searches for a view that can render the dictionary in XML.

Web2py also includes the CRUD application — an acronym which defines the basic or elemental functions of a database. The basic functions of a database include Create, Delete, Update, and Retrieve.

Finally, Web2py has its own customized mechanisms to take care of security issues such as information leakage, broken authentication, and cross-site scripting.

For instance, Web2py handles broken authentication by providing a mechanism for the administrative interface and allows secure sessions when the client is not “ localhost ”.

Installing Web2py

If you already have Web2py installed on your machine, feel free to skip this section.

Binary packages for Web2py are available for operating systems such as Windows, and Linux/Unix . Here is the download link http://www.web2py.com/init/default/download for your convenience.

python web2py

For Linux users:

Step 1 : Download Web2py from http://www.web2py.com/init/default/download

    cd  /home
    mkdir   www-dev    
    cd  www-dev  
    Wget  http://www.web2py.com/examples/static/web2py_src.zip  

Step 2: Unzip x web2py_src.zip after downloading

Step 3 cd web2py — change the directory to web2py to start the server.

python web2py.py

For Windows users:

Step 1 : Download the source package from Web2py official website, save it and unzip it later.

python web2py

Step 2: Within the folder, move your mouse to web2py.exe and double click it.

Step 3: Seconds later, the administrative interface should appear. Enter a custom password. As we can see, the default IP address for the web server is 127.0.0.1. However, you can decide to specify or customize your own IP address. The server port is 8000 (local host).

python web2py

A new window should pop up, displaying a welcome page like the one below:

python web2py

Starting the Administrative Interface:

In order to access administrative functions, we need to sign up to the Web2py then log in. However, we can directly access the administrative files by providing our administrative credentials.

python web2py

After entering the administrator password, we can then have access to the administrative interface. The administrative interface is composed of already installed applications.

By default, the Web2py framework comes with three applications, namely:

  1. Admin application
  2. Examples application
  3. Welcome application

We are currently in the admin application. For the examples application, it is made up of online interactive documentation and an instance of Web2py website. The welcome application, also known as the scaffolding application, contains a basic template for designing any other Web2py application.

Let’s design a basic “HelloWorld!” just to see how it works.

python web2py

Afterward, we edit the default.py by making the following changes to the function index. The default.py represents the controller which allows user interaction and can also read data from the view.

def index():
    """
    example action using the internationalization operator T and flash
    rendered by views/default/index.html or views/generic.html

    if you need a simple wiki simply replace the two lines below with:
    return auth.wiki()
    """
    response.flash = T("Hello World")
    return "Welcome to my world of web development!"

The "Welcome to my world of wed development" is displayed after entering: 127.0.0.1:8000/HelloWorld

Using Web2py for Email Services

With the help of the inbuilt class gluon.tools mail, we can send emails to our contacts or users. Beneath the Example application, click on Welcome Application. Inside, the Welcome Application, under the Models, click on db.py

python web2py

Afterward, define the mailer with this class. Moreover, for debugging purposes, replace the ‘username:password’ with logging.

     from gluon. tools  import Mail   
     mail  =  Mail ()  
     mail = auth.settings.server 
     mail.settings.server  = ‘smtp.project.com:25’  
     mail.settings.sender = ‘xyz@project.com.’  
     mail.settings.login = ‘username: password’      

Sending Email from Web2py

You can use your Gmail account to send messages from one of your accounts to the another mail account.

You must also ensure that you enter the once-entered password Google provides with apps (i.e. Web2py) you intend to use to allow to use Gmail services https://security.google.com/settings/security/apppasswords?pli=1. Failing to do so may lead to errors.

We have already set the configuration settings purposely for sending emails with the mail object, we can now structure the mail.send() syntax to send message(s) to other contacts.

message='None', attachments=[], 
cc=[], bcc=[], reply_to=[], 
sender=None, encoding='utf-8', 
raw=True, 
headers={})

The attributes cc and bcc allows to the sender to include valid email address apart from the main recipient. Below is a simple way to implement the mail.send() to send messages:

mail.send(to=['xyz@project.com'], 
subject='Web2py Project', 
reply_to='xyz@project.com', 
message='This is how Web2py implements mail.send() ')

Wrapping up

Apart from you using the mail.send() to send messages to users or contacts, Web2py provides another module specifically for SMS which differs from the mail.send() because it relies on a third-party service. Web2py is full-stack framework which includes integrated SQL database, and security mechanism to handle common web-application vulnerabilities.

And on top of it all, its ability to send messages from mail services is one of its unique features. You can try your hands with send.mail() to find out how easy it is to use. Finally, I recommend and prefer Web2py framework to other frameworks written and programmable in Python due to its flexible learning curve.


Author's Bio

python web2py

Michael is a budding Cybersecurity Engineer and a technical writer based in Ghana, Africa. He works with AmericanEyes Security as a part-time WordPress security consultant. He is interested in Ruby on Rails and PHP security.

Discover and read more posts from Codementor Team
get started
post comments1Reply
Juraj Dobrik
7 years ago

in PHP i just written function, where this is written in just element order in array defines stuff like adress and toppic, so it just eats correctly set up array and I don’t need to writte a index for that.