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

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

    Enable less secure apps on your gmail account and use (Python>=3.6):

    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    gmailUser = 'XXXXX@gmail.com'
    gmailPassword = 'XXXXX'
    recipient = 'XXXXX@gmail.com'
    
    message = f"""
    Type your message here...
    """
    
    msg = MIMEMultipart()
    msg['From'] = f'"Your Name" <{gmailUser}>'
    msg['To'] = recipient
    msg['Subject'] = "Subject here..."
    msg.attach(MIMEText(message))
    
    try:
        mailServer = smtplib.SMTP('smtp.gmail.com', 587)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(gmailUser, gmailPassword)
        mailServer.sendmail(gmailUser, recipient, msg.as_string())
        mailServer.close()
        print ('Email sent!')
    except:
        print ('Something went wrong...')
    
    0 讨论(0)
  • 2020-11-22 03:52

    I ran into a similar problem and stumbled on this question. I got an SMTP Authentication Error but my user name / pass was correct. Here is what fixed it. I read this:

    https://support.google.com/accounts/answer/6010255

    In a nutshell, google is not allowing you to log in via smtplib because it has flagged this sort of login as "less secure", so what you have to do is go to this link while you're logged in to your google account, and allow the access:

    https://www.google.com/settings/security/lesssecureapps

    Once that is set (see my screenshot below), it should work.

    enter image description here

    Login now works:

    smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo()
    smtpserver.login('me@gmail.com', 'me_pass')
    

    Response after change:

    (235, '2.7.0 Accepted')
    

    Response prior:

    smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp')
    

    Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:

    https://accounts.google.com/DisplayUnlockCaptcha

    Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.

    UPDATE: This doesn't seem to work right away you may be stuck for a while getting this error in smptlib:

    235 == 'Authentication successful'
    503 == 'Error: already authenticated'
    

    The message says to use the browser to sign in:

    SMTPAuthenticationError: (534, '5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qo11sm4014232igb.17 - gsmtp')
    

    After enabling 'lesssecureapps', go for a coffee, come back, and try the 'DisplayUnlockCaptcha' link again. From user experience, it may take up to an hour for the change to kick in. Then try the sign-in process again.

    0 讨论(0)
  • 2020-11-22 03:52
        import smtplib
    
        fromadd='from@gmail.com'
        toadd='send@gmail.com'
    
        msg='''hi,how r u'''
        username='abc@gmail.com'
        passwd='password'
    
        try:
            server = smtplib.SMTP('smtp.gmail.com:587')
            server.ehlo()
            server.starttls()
            server.login(username,passwd)
    
            server.sendmail(fromadd,toadd,msg)
            print("Mail Send Successfully")
            server.quit()
    
       except:
            print("Error:unable to send mail")
    
       NOTE:https://www.google.com/settings/security/lesssecureapps that                                                         should be enabled
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 03:55
    def send_email(user, pwd, recipient, subject, body):
        import smtplib
    
        FROM = user
        TO = recipient if isinstance(recipient, 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)
        try:
            server = smtplib.SMTP("smtp.gmail.com", 587)
            server.ehlo()
            server.starttls()
            server.login(user, pwd)
            server.sendmail(FROM, TO, message)
            server.close()
            print 'successfully sent the mail'
        except:
            print "failed to send mail"
    

    if you want to use Port 465 you have to create an SMTP_SSL object:

    # SMTP_SSL Example
    server_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465)
    server_ssl.ehlo() # optional, called by login()
    server_ssl.login(gmail_user, gmail_pwd)  
    # ssl server doesn't support or need tls, so don't call server_ssl.starttls() 
    server_ssl.sendmail(FROM, TO, message)
    #server_ssl.quit()
    server_ssl.close()
    print 'successfully sent the mail'
    
    0 讨论(0)
提交回复
热议问题