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

后端 未结 14 1678
感情败类
感情败类 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...')
    

提交回复
热议问题