Mail sending program with Python

This program compares the existing IP and the previous IP when Raspberry Pi is restarted, when it is opened or operates from scratch, and sends an e -mail to the desired place if it is different.

On the desktop (if not), it opens a file with the name previous_ip.txt and writes the existing IP and compares the IP, which is written with IP at 1 minute intervals. If there is a difference, it will e -mail. You can maintain the writing-reading authority of this file by pressing the right button on the file.

## program adi : raspberrypi_ip_mail.py
## programin yeri : /home/ozgurcinar/Desktop/raspi5

import os
import smtplib
import subprocess
from email.message import EmailMessage
import time
from datetime import datetime
## calisan servisin adi : /etc/systemd/system/ip_mail_monitor.service
## test icin : python3 /home/ozgurcinar/Desktop/raspi5/raspberrypi_ip_mail.py
## loglar goster journalctl -xe
def get_current_ip():
    return subprocess.check_output(['hostname', '-I']).decode("UTF-8").strip()

def get_previous_ip():
    try:
        file_path = "/home/ozgurcinar/Desktop/previous_ip.txt"
        with open(file_path, "r") as file:
            return file.read().strip()
    except FileNotFoundError:
        return None

def save_current_ip(ip):
    file_path = "/home/ozgurcinar/Desktop/previous_ip.txt"
    with open(file_path, "w") as file:
        file.write(ip)

def send_email(ip):
    from_email_addr = "ormanxxxxx@gmail.com"
    from_email_pass = "xxx xxxx xxxx xxxx" 
    to_email_addr = "ozgurxxxx@gmail.com"

    msg = EmailMessage()
    body = 'Raspberry Pi IP: %s' % ip
    msg.set_content(body)
    msg['From'] = from_email_addr
    msg['To'] = to_email_addr
    msg['Subject'] = 'ORMAN GEZER IP'

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(from_email_addr, from_email_pass)
    server.send_message(msg)
    print('Email sent')
    print('IP Bilgisi Gonderildi:', datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    server.quit()

while True:
    current_ip = get_current_ip()
    previous_ip = get_previous_ip()

    if current_ip != previous_ip:
        send_email(current_ip)
        save_current_ip(current_ip)

    time.sleep(60)  # 1 dakika bekleyin, 5 * 60 = 300 saniye

If you are asked to send an e -mail to the system at the opening of the system, it is necessary to create a service file. And this service file should be provided automatically.

Servis dosya adı ve yolu : /etc/systemd/system/ip_mail_monitor.service

Service Codes :

[Unit]
Description=Raspberry Pi IP Monitor Service
After=network-online.target

[Service]
Type=simple
ExecStartPre=/bin/sleep 60

## after koduna ragmen. 60 sn kadar beklemesi iyi olur, acilista networkun gelmesi vakit aliyor
ExecStart=/usr/bin/python3 /home/ozgurcinar/Desktop/raspi5/raspberrypi_ip_mail.py
WorkingDirectory=/home/ozgurcinar/Desktop/raspi5
Restart=always

[Install]
WantedBy=multi-user.target

## sudo systemctl start ip_mail_monitor.service
## sudo systemctl enable ip_mail_monitor.service

## bu dosyanin kayitli oldugu yolun yazmaya acilmasi
## sudo chmod 777 /etc/systemd/system
## yazmayi geri almak icin
## sudo chmod 755 /etc/systemd/system
## test icin : python3 /home/ozgurcinar/Desktop/raspi5/raspberrypi_ip_mail.py

TEILEN