Need Help in Python Project - Email Multiple file as Attachment

Discussion in 'Other Languages' started by NiravMerchant, Mar 15, 2024.

    
  1. NiravMerchant

    NiravMerchant Active Member


    Hi everyone - i have attached Python Code which should shoot an email with Multiple File as attachment but is is not sending email.
    can anybody help me in this
    ======================================================================
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.base import MIMEBase
    from email import encoders
    import smtplib
    def send_email(sender_email, receiver_email, subject, body, attachment_paths, smtp_server, smtp_port, smtp_username, smtp_password):
    try:
    # Create the email object
    message = MIMEMultipart()
    message["From"] = sender_email
    message["To"] = receiver_email
    message["Subject"] = subject
    # Add the body of the email
    message.attach(MIMEText(body, "plain"))
    # Attach the files
    for attachment_path in attachment_paths:
    attachment = open(attachment_path.strip(), "rb")
    part = MIMEBase("application", "octet-stream")
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header("Content-Disposition", f"attachment; filename= {attachment_path.strip().split('/')[-1]}")
    message.attach(part)
    # Connect to the SMTP server and send the email
    with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(smtp_username, smtp_password)
    server.send_message(message)
    sender_email = "sender@gmail.com"
    print(sender_email)
    receiver_email = "receiver@email.com"
    print(receiver_email)
    subject = "Email with Attachments"
    body = "Dear recipient,\n\nPlease find the attached files.\n\nBest regards,\nSender"
    attachment_paths = ["D:/file.pdf"]
    smtp_server = "smtp.gmail.com"
    print(smtp_server)
    smtp_port = 587
    print(smtp_port)
    smtp_username = "sender@gmail.com"
    smtp_password = "email password"
    except Exception as e:
    print(f"An error occurred: {e}")
     


  2. Sai Vineeth

    Sai Vineeth Active Member


    your python code is not indented and its hard to understand what your code does

    I think you just defined method(send_email) but never called/Invoked it

    This not the correct site to post python queries, use stack overflow.
     


Share This Page