How do I send attachments using SMTP?

后端 未结 6 905
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 01:55

I want to write a program that sends email using Python\'s smtplib. I searched through the document and the RFCs, but couldn\'t find anything related to attachments. Thus,

6条回答
  •  醉酒成梦
    2020-12-01 02:22

    Here is an example of a message with a PDF attachment, a text "body" and sending via Gmail.

    # Import smtplib for the actual sending function
    import smtplib
    
    # For guessing MIME type
    import mimetypes
    
    # Import the email modules we'll need
    import email
    import email.mime.application
    
    # Create a text/plain message
    msg = email.mime.Multipart.MIMEMultipart()
    msg['Subject'] = 'Greetings'
    msg['From'] = 'xyz@gmail.com'
    msg['To'] = 'abc@gmail.com'
    
    # The main body is just another attachment
    body = email.mime.Text.MIMEText("""Hello, how are you? I am fine.
    This is a rather nice letter, don't you think?""")
    msg.attach(body)
    
    # PDF attachment
    filename='simple-table.pdf'
    fp=open(filename,'rb')
    att = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
    fp.close()
    att.add_header('Content-Disposition','attachment',filename=filename)
    msg.attach(att)
    
    # send via Gmail server
    # NOTE: my ISP, Centurylink, seems to be automatically rewriting
    # port 25 packets to be port 587 and it is trashing port 587 packets.
    # So, I use the default port 25, but I authenticate. 
    s = smtplib.SMTP('smtp.gmail.com')
    s.starttls()
    s.login('xyz@gmail.com','xyzpassword')
    s.sendmail('xyz@gmail.com',['xyz@gmail.com'], msg.as_string())
    s.quit()
    

提交回复
热议问题