RPI+ Camera + Email Integration

import subprocess
import yagmail
import os

def capture_image_libcamera(filename="captured.jpg"):
    # Capture image using libcamera-still command
    subprocess.run(["libcamera-still", "-o", filename, "--nopreview"], check=True)

def send_email_with_attachment(sender, app_password, receiver, subject, message, attachment_path):
    yag = yagmail.SMTP(user=sender, password=app_password)
    yag.send(
        to=receiver,
        subject=subject,
        contents=message,
        attachments=attachment_path
    )
    print("Email sent successfully!")

def main():
    image_file = "captured.jpg"
    sender_email = "your_email@gmail.com"
    app_password = "your_app_password"
    receiver_email = "receiver@example.com"
    subject = "Captured Image from Raspberry Pi"
    message = "Hi, this is the captured image attached."

    # Capture image
    print("Capturing image...")
    capture_image_libcamera(image_file)

    # Send email with attachment
    print("Sending email...")
    send_email_with_attachment(sender_email, app_password, receiver_email, subject, message, image_file)

    # Optionally remove image after sending
    if os.path.exists(image_file):
        os.remove(image_file)
        print("Temporary image file removed.")

if __name__ == "__main__":
    main()

Leave a Reply

Your email address will not be published. Required fields are marked *