How to send a file to mail using python script

You can send a file to an email using Python's smtplib library. Here's a simple example:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE
from email import encoders
import os

def send_email(subject, message, from_addr, to_addr, files=None, server="smtp.gmail.com", port=587, username="", password=""):
    msg = MIMEMultipart()
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Subject'] = subject

    body = message
    msg.attach(MIMEText(body, 'plain'))

    if files:
        for file in files:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(open(file, 'rb').read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
            msg.attach(part)

    server = smtplib.SMTP(server, port)
    server.starttls()
    server.login(username, password)
    text = msg.as_string()
    server.sendmail(from_addr, to_addr, text)
    server.quit()

# Example usage:
subject = "Test email with attachment"
message = "This is a test email with attachment."
from_addr = "[email protected]"
to_addr = "[email protected]"
files = ["path_to_your_file.txt", "path_to_your_image.jpg"]
send_email(subject, message, from_addr, to_addr, files)

In this script, you need to replace "[email protected]", "[email protected]", "path_to_your_file.txt", and "path_to_your_image.jpg" with your actual email address, the recipient's email address, and the paths to the files you want to send.

Please note that you need to enable "Less secure app access" in your Google account settings if you're using Gmail. Also, be careful when sharing your password.

If you're using a Gmail account, you might need to allow "Less secure app access" in your account settings. You can do this by following these steps:

  1. Go to your Google Account settings.
  2. Click on "Security" from the menu on the left.
  3. Scroll down to the "Less secure app access" section.
  4. Toggle the switch to "On".

Also, be aware that storing your password in plain text is not secure. You should consider using a more secure method to store and use your password, such as environment variables or a secrets manager.