How to send email attachments?

前端 未结 13 1187
梦谈多话
梦谈多话 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:23

    Gmail version, working with Python 3.6 (note that you will need to change your Gmail settings to be able to send email via smtp from it:

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.mime.application import MIMEApplication
    from os.path import basename
    
    
    def send_mail(send_from: str, subject: str, text: str, 
    send_to: list, files= None):
    
        send_to= default_address if not send_to else send_to
    
        msg = MIMEMultipart()
        msg['From'] = send_from
        msg['To'] = ', '.join(send_to)  
        msg['Subject'] = subject
    
        msg.attach(MIMEText(text))
    
        for f in files or []:
            with open(f, "rb") as fil: 
                ext = f.split('.')[-1:]
                attachedfile = MIMEApplication(fil.read(), _subtype = ext)
                attachedfile.add_header(
                    'content-disposition', 'attachment', filename=basename(f) )
            msg.attach(attachedfile)
    
    
        smtp = smtplib.SMTP(host="smtp.gmail.com", port= 587) 
        smtp.starttls()
        smtp.login(username,password)
        smtp.sendmail(send_from, send_to, msg.as_string())
        smtp.close()
    

    Usage:

    username = 'my-address@gmail.com'
    password = 'top-secret'
    default_address = ['my-address2@gmail.com'] 
    
    send_mail(send_from= username,
    subject="test",
    text="text",
    send_to= None,
    files= # pass a list with the full filepaths here...
    )
    

    To use with any other email provider, just change the smtp configurations.

提交回复
热议问题