How to send email attachments?

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

    from email.mime.multipart import MIMEMultipart
    from email.mime.image import MIMEImage
    from email.mime.text import MIMEText
    import smtplib
    
    msg = MIMEMultipart()
    
    password = "password"
    msg['From'] = "from_address"
    msg['To'] = "to_address"
    msg['Subject'] = "Attached Photo"
    msg.attach(MIMEImage(file("abc.jpg").read()))
    file = "file path"
    fp = open(file, 'rb')
    img = MIMEImage(fp.read())
    fp.close()
    msg.attach(img)
    server = smtplib.SMTP('smtp.gmail.com: 587')
    server.starttls()
    server.login(msg['From'], password)
    server.sendmail(msg['From'], msg['To'], msg.as_string())
    server.quit()
    

提交回复
热议问题