Failing to send email with the Python example

后端 未结 10 944
南旧
南旧 2020-12-04 15:56

I\'ve been trying (and failing) to figure out how to send email via Python.

Trying the example from here: http://docs.python.org/library/smtplib.html#smtplib.SMTP

10条回答
  •  遥遥无期
    2020-12-04 16:36

    Here's a simple throw away solution. Meant to paste this earlier, but fell asleep at my chair.

    
    import smtplib
    import email
    import os
    
    username = "user@gmail.com"
    passwd = "password"
    
    def mail(to, subject, text, attach):
       msg = MIMEMultipart()
    
       msg['From'] = username
       msg['To'] = to
       msg['Subject'] = subject
    
       msg.attach(MIMEText(text)) 
    
       part = MIMEBase('application', 'octet-stream')
       part.set_payload(open(attach, 'rb').read())
       Encoders.encode_base64(part)
       part.add_header('Content-Disposition',
               'attachment; filename="%s"' % os.path.basename(attach))
       msg.attach(part)
    
       server = smtplib.SMTP("smtp.gmail.com", 495)
       server.ehlo()
       server.starttls()
       server.ehlo()
       server.login(username, passwd)
       server.sendmail(username, to, msg.as_string())
       server.close()
    
    mail("you", "hi", "hi", "webcam.jpg")
    
    

    It's my assumption that most people on this thread that have had successful attempts with their code aren't on win32. ;)

    *edit: See http://docs.python.org/library/email-examples.html for some good "official" examples.

提交回复
热议问题