How to send an email with Gmail as provider using Python?

后端 未结 14 1893
感情败类
感情败类 2020-11-22 03:29

I am trying to send email (Gmail) using python, but I am getting following error.

Traceback (most recent call last):  
File \"emailSend.py\", line 14, in <         


        
14条回答
  •  日久生厌
    2020-11-22 03:53

    great answer from @David, here is for Python 3 without the generic try-except:

    def send_email(user, password, recipient, subject, body):
    
        gmail_user = user
        gmail_pwd = password
        FROM = user
        TO = recipient if type(recipient) is list else [recipient]
        SUBJECT = subject
        TEXT = body
    
        # Prepare actual message
        message = """From: %s\nTo: %s\nSubject: %s\n\n%s
        """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_pwd)
        server.sendmail(FROM, TO, message)
        server.close()
    

提交回复
热议问题