I tried to make a simple mail sending application with tkinter of Python

Introduction

In this article, we will develop an application using Python. The standard library tkinter is used as the GUI library. The standard library smtplib is used for sending mail. If you understand python to some extent by reading this article, you should be able to learn how to use tkinter and smtplib to some extent.

What is tkinter

It is one of the standard Python libraries. A library for building GUI applications. A GUI library featuring a simple grammar and quick startup.

Creating a window

First, let's create a window that will be.

import tkinter as tk

if __name__ == "__main__":
    root = tk.Tk()
    root.mainloop()

01_ウィンドウ.png

Creating a screen

We will create a class that inherits the Frame class in order to write with object orientation in mind. Create the necessary parts (widgets) in create_widgets (), arrange them, and create the screen.

import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.pack()

        #Set screen size and title
        master.geometry("300x200")
        master.title("Simple email sending app")

        self.create_widgets()

    #Method to generate widget
    def create_widgets(self):
        self.label = tk.Label(self,text="Simple email sending app")
        self.label.grid(row=0, column=0, columnspan=3)

        self.to_label = tk.Label(self, text="destination:")
        self.to_entry = tk.Entry(self, width=20)
        self.to_label.grid(row=1, column=0)
        self.to_entry.grid(row=1, column=1, columnspan=2)

        self.subject_label = tk.Label(self, text="subject:")
        self.subject_entry = tk.Entry(self, width=20)
        self.subject_label.grid(row=2, column=0)
        self.subject_entry.grid(row=2, column=1, columnspan=2)

        self.body_label = tk.Label(self, text="Text:")
        self.body_text = tk.Entry(self, width=20)
        self.body_label.grid(row=3, column=0)
        self.body_text.grid(row=3, column=1, columnspan=2)

        self.button = tk.Button(self, text="Send")
        self.button.grid(row=4, column=2, sticky=tk.E, pady=10)

if __name__ == "__main__":
    root = tk.Tk()
    Application(master=root)
    root.mainloop()

02_画面レイアウト完成.png

Event processing settings

Set event processing for the send button. Event processing is the processing (method) that is called when the button is pressed. Set event processing using a lambda expression in the argument command when the button is generated. Set the process to output the input value to the standard output (console) for the time being.

    #Method to generate widget
    def create_widgets(self):
    
	#~ Omitted ~
    
        self.button = tk.Button(self, text="Send", command=lambda:self.click_event())
        self.button.grid(row=4, column=2, sticky=tk.E, pady=10)

    def click_event(self):
        to = self.to_entry.get()
        subject = self.subject_entry.get()
        body = self.body_text.get()

        print(f"destination:{to}")
        print(f"subject:{subject}")
        print(f"Text:{body}")

03_イベント処理.png

Console display result

destination:[email protected]
subject:About the other day's meeting
Text:Thank you for the meeting the other day.

Preparing to send an email

A little preparation is required before creating the email sending process. This time, I will create it assuming that it will be sent from a Gmail account. First of all, if you do not have a Gmail account, please create one from the link below. If you already have one, we recommend that you get a sub-account for development. (As you can see just below, you need to lower your account security settings a bit.) https://accounts.google.com/SignUp

If you already have an account, or if you're done creating a new one, you'll need to make a few changes to your account settings to send emails from the Python program. Follow the steps below to display the "Account Setting Screen". 04_アカウント設定.png

Then select Security from the menu on the left. 05_セキュリティメニュー.png

Scroll down to the bottom of the screen and turn on "Access to insecure apps". 06_安全性の低いアプリ.png

Now you're ready to log in to Gmail from your Python program and send your email.

Email sending process

I will make the mail transmission processing part. First, import the library required for sending emails.

from smtplib import SMTP
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

Next, we will create a method for sending emails. The part that changes dynamically each time you send an email is received as a method argument. A constant is defined in the method for a value that does not change each time an email is sent. The ID and PASS will be the sender's Gmail email address and password. Please set this according to your own environment.

    #Email sending process
    def send_mail(self, to, subject, body):
        #Define the information required for transmission with a constant
        ID = "mail_address"
        PASS = "password"
        HOST = "smtp.gmail.com"
        PORT = 587

        #Set email body
        msg = MIMEMultipart()
        msg.attach(MIMEText(body, "html"))

        #Set subject, source address, destination address
        msg["Subject"] = subject
        msg["From"] = ID
        msg["To"] = to

        #Connect to the SMTP server and start TLS communication
        server=SMTP(HOST, PORT)
        server.starttls()

        server.login(ID, PASS) #Login authentication process

        server.send_message(msg)    #Email sending process

        server.quit()       #TLS communication end

Linking event processing

Finally, if you change the event processing part to call the method created earlier, the simple mail sending application is completed.

    def click_event(self):
        to = self.to_entry.get()
        subject = self.subject_entry.get()
        body = self.body_text.get()

        # print(f"destination:{to}")
        # print(f"subject:{subject}")
        # print(f"Text:{body}")
    
        self.send_mail(to=to, subject=subject, body=body)

Completed source code

The completed source code is as follows.

import tkinter as tk
from smtplib import SMTP
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

class Application(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.pack()

        #Set screen size and title
        master.geometry("300x200")
        master.title("Simple email sending app")

        self.create_widgets()

    #Method to generate widget
    def create_widgets(self):
        self.label = tk.Label(self,text="Simple email sending app")
        self.label.grid(row=0, column=0, columnspan=3)

        self.to_label = tk.Label(self, text="destination:")
        self.to_entry = tk.Entry(self, width=20)
        self.to_label.grid(row=1, column=0)
        self.to_entry.grid(row=1, column=1, columnspan=2)

        self.subject_label = tk.Label(self, text="subject:")
        self.subject_entry = tk.Entry(self, width=20)
        self.subject_label.grid(row=2, column=0)
        self.subject_entry.grid(row=2, column=1, columnspan=2)

        self.body_label = tk.Label(self, text="Text:")
        self.body_text = tk.Entry(self, width=20)
        self.body_label.grid(row=3, column=0)
        self.body_text.grid(row=3, column=1, columnspan=2)

        self.button = tk.Button(self, text="Send", command=lambda:self.click_event())
        self.button.grid(row=4, column=2, sticky=tk.E, pady=10)

    def click_event(self):
        to = self.to_entry.get()
        subject = self.subject_entry.get()
        body = self.body_text.get()
    
        self.send_mail(to=to, subject=subject, body=body)

    #Email sending process
    def send_mail(self, to, subject, body):
        #Define the information required for transmission with a constant
        ID = "mail_address"
        PASS = "password"
        HOST = "smtp.gmail.com"
        PORT = 587

        #Set email body
        msg = MIMEMultipart()
        msg.attach(MIMEText(body, "html"))

        #Set subject, source address, destination address
        msg["Subject"] = subject
        msg["From"] = ID
        msg["To"] = to

        #Connect to the SMTP server and start TLS communication
        server=SMTP(HOST, PORT)
        server.starttls()   #TLS communication started

        server.login(ID, PASS) #Login authentication process

        server.send_message(msg)    #Email sending process

        server.quit()       #TLS communication end

if __name__ == "__main__":
    root = tk.Tk()
    Application(master=root)
    root.mainloop()

Finally

If you are interested in creating an email sending application after trying it all, restore the security settings of your Google account.

Recommended Posts

I tried to make a simple mail sending application with tkinter of Python
I tried to make a 2channel post notification application with Python
I tried to make a todo application using bottle with python
I tried to make a stopwatch using tkinter in python
I tried to make GUI tic-tac-toe with Python and Tkinter
[Python] I tried to automatically create a daily report of YWT with Outlook mail
[5th] I tried to make a certain authenticator-like tool with python
Rubyist tried to make a simple API with Python + bottle + MySQL
[2nd] I tried to make a certain authenticator-like tool with python
I tried to make a regular expression of "amount" using Python
I tried to make a regular expression of "time" using Python
[3rd] I tried to make a certain authenticator-like tool with python
I tried to create a list of prime numbers with python
I tried to make a regular expression of "date" using Python
I tried to make a periodical process with Selenium and Python
[4th] I tried to make a certain authenticator-like tool with python
[1st] I tried to make a certain authenticator-like tool with python
I tried to make a mechanism of exclusive control with Go
[Python] I tried to make an application that calculates salary according to working hours with tkinter
I want to make a game with Python
Python: I tried to make a flat / flat_map just right with a generator
I tried to make a calculator with Tkinter so I will write it
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
I tried to discriminate a 6-digit number with a number discrimination application made with python
I tried to draw a route map with Python
I tried to automatically generate a password with Python3
I tried to make an OCR application with PySimpleGUI
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
[Patent analysis] I tried to make a patent map with Python without spending money
[ES Lab] I tried to develop a WEB application with Python and Flask ②
I tried to make a simple image recognition API with Fast API and Tensorflow
I tried to find the entropy of the image with python
I made a simple typing game with tkinter in Python
I tried to make various "dummy data" with Python faker
I tried various methods to send Japanese mail with Python
I made a simple book application with python + Flask ~ Introduction ~
I tried to implement the mail sending function in Python
I tried a stochastic simulation of a bingo game with Python
I tried to make a simple text editor using PyQt
I tried to make something like a chatbot with the Seq2Seq model of TensorFlow
I tried to make a real-time sound source separation mock with Python machine learning
[Mac] I want to make a simple HTTP server that runs CGI with Python
I tried to make a function to retrieve data from database column by column using sql with sqlite3 of python [sqlite3, sql, pandas]
[1 hour challenge] I tried to make a fortune-telling site that is too suitable with Python
[Python] I tried to implement stable sorting, so make a note
[Python] I want to make a 3D scatter plot of the epicenter with Cartopy + Matplotlib!
[Python] A memo that I tried to get started with asyncio
I tried sending an email with python.
I tried to fix "I tried stochastic simulation of bingo game with Python"
I tried a functional language with Python
I tried to make a generator that generates a C # container class from CSV with Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
[Python] Simple Japanese ⇒ I tried to make an English translation tool
I tried to make a Web API
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I tried to improve the efficiency of daily work with Python
I tried to make a strange quote for Jojo with LSTM
I tried to automatically collect images of Kanna Hashimoto with Python! !!
I made a simple blackjack with Python
I tried to make an image similarity function with Python + OpenCV
[Python] I tried to make a simple program that works on the command line using argparse.