How to send email attachments?

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

    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    import smtplib
    import mimetypes
    import email.mime.application
    
    smtp_ssl_host = 'smtp.gmail.com'  # smtp.mail.yahoo.com
    smtp_ssl_port = 465
    s = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
    s.login(email_user, email_pass)
    
    
    msg = MIMEMultipart()
    msg['Subject'] = 'I have a picture'
    msg['From'] = email_user
    msg['To'] = email_user
    
    txt = MIMEText('I just bought a new camera.')
    msg.attach(txt)
    
    filename = 'introduction-to-algorithms-3rd-edition-sep-2010.pdf' #path to file
    fo=open(filename,'rb')
    attach = email.mime.application.MIMEApplication(fo.read(),_subtype="pdf")
    fo.close()
    attach.add_header('Content-Disposition','attachment',filename=filename)
    msg.attach(attach)
    s.send_message(msg)
    s.quit()
    

    For explanation, you can use this link it explains properly https://medium.com/@sdoshi579/to-send-an-email-along-with-attachment-using-smtp-7852e77623

提交回复
热议问题