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

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

提交回复
热议问题