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

后端 未结 14 1992
感情败类
感情败类 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:54

    This Works

    Create Gmail APP Password!

    After you create that then create a file called sendgmail.py

    Then add this code:

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    # =============================================================================
    # Created By  : Jeromie Kirchoff
    # Created Date: Mon Aug 02 17:46:00 PDT 2018
    # =============================================================================
    # Imports
    # =============================================================================
    import smtplib
    
    # =============================================================================
    # SET EMAIL LOGIN REQUIREMENTS
    # =============================================================================
    gmail_user = 'THEFROM@gmail.com'
    gmail_app_password = 'YOUR-GOOGLE-APPLICATION-PASSWORD!!!!'
    
    # =============================================================================
    # SET THE INFO ABOUT THE SAID EMAIL
    # =============================================================================
    sent_from = gmail_user
    sent_to = ['THE-TO@gmail.com', 'THE-TO@gmail.com']
    sent_subject = "Where are all my Robot Women at?"
    sent_body = ("Hey, what's up? friend!\n\n"
                 "I hope you have been well!\n"
                 "\n"
                 "Cheers,\n"
                 "Jay\n")
    
    email_text = """\
    From: %s
    To: %s
    Subject: %s
    
    %s
    """ % (sent_from, ", ".join(sent_to), sent_subject, sent_body)
    
    # =============================================================================
    # SEND EMAIL OR DIE TRYING!!!
    # Details: http://www.samlogic.net/articles/smtp-commands-reference.htm
    # =============================================================================
    
    try:
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(gmail_user, gmail_app_password)
        server.sendmail(sent_from, sent_to, email_text)
        server.close()
    
        print('Email sent!')
    except Exception as exception:
        print("Error: %s!\n\n" % exception)
    

    So, if you are successful, will see an image like this:

    I tested by sending an email from and to myself.

    Note: I have 2-Step Verification enabled on my account. App Password works with this! (for gmail smtp setup, you must go to https://support.google.com/accounts/answer/185833?hl=en and follow the below steps)

    This setting is not available for accounts with 2-Step Verification enabled. Such accounts require an application-specific password for less secure apps access.

提交回复
热议问题