How to send email attachments?

前端 未结 13 920
梦谈多话
梦谈多话 2020-11-22 01:14

I am having problems understanding how to email an attachment using Python. I have successfully emailed simple messages with the smtplib. Could someone please e

13条回答
  •  无人共我
    2020-11-22 01:32

    You can also specify the type of attachment you want in your e-mail, as an example I used pdf:

    def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):
        ## credits: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
        from socket import gethostname
        #import email
        from email.mime.application import MIMEApplication
        from email.mime.multipart import MIMEMultipart
        from email.mime.text import MIMEText
        import smtplib
        import json
    
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        with open(password_path) as f:
            config = json.load(f)
            server.login('me@gmail.com', config['password'])
            # Craft message (obj)
            msg = MIMEMultipart()
    
            message = f'{message}\nSend from Hostname: {gethostname()}'
            msg['Subject'] = subject
            msg['From'] = 'me@gmail.com'
            msg['To'] = destination
            # Insert the text to the msg going by e-mail
            msg.attach(MIMEText(message, "plain"))
            # Attach the pdf to the msg going by e-mail
            with open(path_to_pdf, "rb") as f:
                #attach = email.mime.application.MIMEApplication(f.read(),_subtype="pdf")
                attach = MIMEApplication(f.read(),_subtype="pdf")
            attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))
            msg.attach(attach)
            # send msg
            server.send_message(msg)
    

    inspirations/credits to: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script

提交回复
热议问题