avatarData Dev Backyard

Summary

The web content provides a comprehensive guide on creating an email form using Flet (Flutter for Python), detailing the process from setting up a Python virtual environment to building the form structure and sending emails without attachments.

Abstract

The tutorial presented on the website is a two-part guide aimed at entrepreneurs and engineers who wish to build an email form for their website without relying on third-party services. The first part of the tutorial focuses on using Flet, a Python wrapper for Flutter, to create a basic email form. It begins with the prerequisites, which include familiarity with Python and the creation of a virtual environment. The author then outlines the project structure, emphasizing the importance of separating concerns by organizing utility functions and environment variables into dedicated files. The tutorial progresses to the implementation of an email sending function using Python's smtplib and the configuration of Gmail's two-factor authentication for application passwords. The main application file, main.py, is described with code snippets demonstrating the use of TextField and ElevatedButton elements from Flet to construct the form interface. The author also provides instructions on handling button clicks to send emails and show confirmation messages. Screenshots of the form and the received email are included to illustrate the functionality. The article concludes with a full example of the main.py content and a promotion for the author's YouTube channel and Medium articles.

Opinions

  • The author advocates for the use of Flet as a free and customizable solution for building web forms.
  • Emphasizing the importance of separating concerns in software development, the author suggests using dedicated files for constants, helpers, and environment variables.
  • The author encourages the use of Python virtual environments to manage project dependencies effectively.
  • The tutorial promotes the idea of creating a Gmail application password for secure email transmission through third-party applications.
  • The author values the educational content they provide, inviting readers to subscribe to their YouTube channel and follow them on Medium for more technical articles.
  • A cost-effective AI service, ZAI.chat, is recommended as an alternative to ChatGPT Plus (GPT-4), highlighting the author's opinion on the value of this service.

Email Form Using Flet — Part 1

As a entrepreneur or engineer you might find the need at some point to build an email form on your Website. There might be tons of services out there which help you with creating forms for this purpose; however, in case you would like to program it yourself, it is also possible and free to do so. In this tutorial, I would like to show you how to create an email Form using Flet (Flutter in Python):

_ In Part1 of the tutorial, I am creating an email Form using Flet. This email Form does not contain an attachment.

_ In Part 2 of the tutorial, I will be extending the email form to support the attachment.

Please take a moment to subscribe to my YouTube channel at https://www.youtube.com/@datadevbackyard to receive the latest educational content. Thank you.

Perquisites:

The only requirement for this tutorial is some familiarity with Python, and having a virtual environment of your choice. You can create a virtual environment using Python through “python -m venv venv_name”. So for example, I create a virtual environment through the VSCode by applying the command “python -m venv flet_email_form”. A folder like following should be created in the active directory like the following:

Virtual environment

You can activate the virtual environment by writing “.\flet_email_form\Scripts\Activate” and immediately you should be able to see the virtual environment activated like the following:

flet_email_form is the virtual environment

Please proceed with install Flet by writing “pip install flet” in the corresponding virtual environment. Flet should be installed in a around a minute.

Building the First Project Structure

Let us create a couple of folders and files in the root directory like following:

Our project structure

In the following a rough overview of the project structure is described:

_ Utils: is a module and holds our utility and commons functionalities

__ Constants.py holds all our Python constant values.

__ helper.py keeps the utility functions like function responsible for sending emails.

_ .env holds our environment variables like the Gmail password application.

_ .gitignore: protects us to keep confidential information locally and not pushing to the remote repository.

_ main.py: it is the main entry point to our application.

We can keep the separation of concerns from the beginning, and consider a function for sending emails. The send_email function which is located in the helper.py file is responsible for sending emails, and we will call it later in the main.py file:

send_email function which will be called in the main.py file

In the above function, we construct a message object using the MIMEMultipart(), and we add components to it like sender, receiver, subject and an attachment, if any. The email function uses the smtplib protocol to send an email, and it uses server.login, to login to a server using the application password from Gmail, and then uses the server.sendmail() to send the email to the destination.

For creating a Gmail password for your application, please go to your Gmail setting, and click on security, then click on the two factor authentication, and the bottom of the screen, you should be able to create a password in which you can copy and paste in the .env file for your SENDER_PASSWORD.

After writing the send_email function, we need to fill in the .env file with the environment values which are mainly confidential like the Gmail Application password. Below is an example of the variables which can be considered for the .env file:

environment variables

After your changes to the .env file, you should be able to read the ENV variables to your Python code through the following code snippet.

Code snippet to read the environment variables

Of course, you need to install python-environ thorough “pip install python-environ” in the activated virtual environment. The benefit of using a separate file for your constant variables is a) separation of concerns b) giving more meaning to your variable names and usages. Last but not least, you might fill the .gitignore file with .env value in order to avoid pushing confidential information like SENDER_PASSWORD to a remote repository:

Content of the .gitignore file

Building an Email Form Without Attachment

In the part 1 of the tutorial, we would like to build a form (without attachment), therefore, I would like to progress with completing the main.py file:

For building an email form (without Attachment), we can use two basic elements from Flet: a) TextField b) ElevatedButton.

Creating a couple of TextField and Button for the email form

In the above, I created a subject_field holding the subject of the email, full_name holding the name of the sender, receiver_address holding the address of the receiver and message_body keeping the body of the message. send_button is responsible for sending the email. After send button is clicked, the email_sent_message will get a value of “email_sent”.

Now, it’s needed to add the element to the Flet application through the page.add(), and then we need to update the page thorugh page.update(). In the following, I add each of the elements; however, I’m using an ft.Container and ft.Column elements in order to keep the form in only one column, and to give it a little bit of styling:

Adding elements to the Flet app and updating the page

Still, I’ve not brought the definition of the btn_clicked, and I would like to explain it in the following:

button clicked function

when the button is clicked, the message_body and subject_field get values through the .value parameter, and then the send_email function is called. We pass through the required input parameters of the send_email function, and if the email is sent, then email_sent_message gets a value of “email_sent”. extra_info contians the message body of the email plus a little bit more information text.

Below is an example of the filled form with some test information:

Email Form without Attachment using Flet

And below you can see the email which is received in the Gmail mail box:

Sent Email!

Below you can find the full content of the main.py file:

import flet as ft 
from Utils.helper import send_email
from Utils.Constants import (SMTP_SEVER_ADDRESS, SENDER_ADDRESS, PORT, SENDER_PASSWORD)

def main(page):

    def btn_clicked(e):
        if not message_body.value and not subject_field.value:

            message_body.value = "Pleaes enter a message"
            subject_field.value = "Please enter a subject"
        else:
            extra_info = """ 

            ------------------------------------------

            Email Addres of sender {} \n

            Sender Full Name {} \n


            ------------------------------------------ \n \n

            """.format(SENDER_ADDRESS, full_name.value)

            message = extra_info +  message_body.value

            email_sent = send_email(

                SENDER_ADDRESS, SENDER_PASSWORD,receiver_address.value, SMTP_SEVER_ADDRESS,
                PORT, message ,
                subject_field.value, attachment=None
            )
            if email_sent:
                email_sent_message.value = 'Email is sent!'
                page.add(email_sent_message)
                page.update()




    subject_field = ft.TextField(label= "Subject")
    full_name = ft.TextField(label="Full Name")
    receiver_address = ft.TextField(label="Email Address")
    message_body = ft.TextField(label="Message Body", multiline=True)
    send_button = ft.ElevatedButton("Send", on_click = btn_clicked)
    email_sent_message = ft.Text("")
    
    page.add(
        
        ft.Container(content = ft.Column(

        [
            ft.Container(content = subject_field, width = 500, alignment=ft.alignment.center),
            ft.Container(content= full_name, width = 500, alignment=ft.alignment.center),
            ft.Container(content= receiver_address, width = 500, alignment=ft.alignment.center),
            ft.Container(content= message_body, width = 500, alignment=ft.alignment.center),
            ft.Container(content= send_button, width = 500, alignment=ft.alignment.center)
        ]
    )
        ,  alignment = ft.alignment.center, width = 500, bgcolor=ft.colors.YELLOW)

    )

        
    page.update()

ft.app(target=main)

Please take a moment to subscribe to my YouTube channel at https://www.youtube.com/@datadevbackyard to receive the latest educational content. Thank you.

I publish every week technical articles in this channel, so please follow me on Medium, and subscribe to my YouTube channel. You may check my other articles from my listings related to Spark and Scala, Streamlit, React, Django, AWS, Machine Learning, Startup, Cheatsheets and miscellaneous development topics.

Flet
Flutter
Startup
Python
Data Science
Recommended from ReadMedium