Tuesday, November 26, 2024

Send mail from Raspberry PI via Python

In this small tutorial we will send an email via a python

2.) create a test script via

sudo nano sendtestmail.py

3.) copy the following inside the script:

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

# E-Mail-Details
sender_email = "sender email address"
receiver_email = "receiver email address"
password = "your password"
user_name = "your login name; might be the same as the email address"
host_name = "the hostname which needs to be used"

# E-Mail-Header
subject = "The subject from the mail"
body = "The body from the mail"

# Create email
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject

# add text to the mail
message.attach(MIMEText(body, "plain"))

# conntect to SMTP server and send mail
try:
    server = smtplib.SMTP(host_name, 587)
    server.starttls()  # activate TLS
    server.login(user_name, password)
    server.sendmail(sender_email, receiver_email, message.as_string())
    print("email send sucessfully!")
except Exception as e:
    print(f"Error sending mail: {e}")
finally:
    server.quit()

4.) Test the script via

sudo python sendtestmail.py

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

35FollowersFollow
- Advertisement -

Latest Articles