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):
    # 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.add_header("Content-Disposition", f"attachment; filename= {attachment_path.strip().split('/')[-1]}")
    # Connect to the SMTP server and send the email
    with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.login(smtp_username, smtp_password)
    sender_email = ""
    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_port = 587
    smtp_username = ""
    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