add excel file attachment when sending python email

前端 未结 4 588
离开以前
离开以前 2020-11-28 07:25

How do i add a document attachment when sending an email with python ? i get the email to send (please ignore: i am looping the email to send every 5 seconds, only for testi

4条回答
  •  借酒劲吻你
    2020-11-28 08:16

    To send an attachment create a MIMEMultipart object and add the attachment to that. Here is an example from the python email examples.

    # Import smtplib for the actual sending function
    import smtplib
    
    # Here are the email package modules we'll need
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    
    COMMASPACE = ', '
    
    # Create the container (outer) email message.
    msg = MIMEMultipart()
    msg['Subject'] = 'Our family reunion'
    # me == the sender's email address
    # family = the list of all recipients' email addresses
    msg['From'] = me
    msg['To'] = COMMASPACE.join(family)
    msg.preamble = 'Our family reunion'
    
    # Assume we know that the image files are all in PNG format
    for file in pngfiles:
        # Open the files in binary mode.  Let the MIMEImage class automatically
        # guess the specific image type.
        fp = open(file, 'rb')
        img = MIMEImage(fp.read())
        fp.close()
        msg.attach(img)
    
    # Send the email via our own SMTP server.
    s = smtplib.SMTP('localhost')
    s.sendmail(me, family, msg.as_string())
    s.quit()
    

提交回复
热议问题