代码之家  ›  专栏  ›  技术社区  ›  mmewtwosaysbye

如何在smptlib中向电子邮件添加文件附件?

  •  0
  • mmewtwosaysbye  · 技术社区  · 10 月前

    我已经制作了一个电子邮件发送脚本,但我不知道如何使用它发送文件。帮助!

    filename = 'image.png'
    my_user = '[email protected]'  # 
    my_pass = 'my app code' 
    
    smtpserver = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    smtpserver.ehlo()
    smtpserver.login(my_user, my_pass)
    
    sent_from = my_user
    sent_to = 'myotheremail'  #  Send it to self (as test)
    email_text = 'This is a test'
    smtpserver.sendmail(sent_from, sent_to, email_text, filename)
    
    smtpserver.close()
    
    1 回复  |  直到 10 月前
        1
  •  1
  •   Prabhat Kumar    10 月前

    要使用Python发送带有附件的电子邮件,您需要 除了smtplib之外,还可以使用电子邮件模块。 这个 smtplib.sendmail()方法 不直接处理附件,因此您需要构建包含附件的电子邮件。

    我为您提供了下面的完整代码供您参考,您可以根据自己的意愿进行编辑:

    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.base import MIMEBase
    from email import encoders
    
    # Email configuration
    filename = 'image.png'
    my_user = '[email protected]'
    my_pass = 'my app code'
    sent_to = '[email protected]'  # Use your actual recipient email
    
    # Creating email message
    msg = MIMEMultipart()
    msg['From'] = my_user
    msg['To'] = sent_to
    msg['Subject'] = 'Subject: Test Email with Attachment'
    
    # Email body text
    body = 'This is a test email with an attachment.'
    msg.attach(MIMEText(body, 'plain'))
    
    # Attach the file
    attachment = open(filename, 'rb')
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(attachment.read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', f'attachment; filename= {filename}')
    msg.attach(part)
    
    # Send the email
    try:
        smtpserver = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        smtpserver.login(my_user, my_pass)
        smtpserver.send_message(msg)
        print("Email sent successfully!")
    except Exception as e:
        print(f"Failed to send email: {e}")
    finally:
        smtpserver.quit()
        attachment.close()
    

    如果这段代码解决了你的问题,那么请为我的答案投上赞成票(点击顶部和旁边的上箭头)。