首页 文章

Python smtp从gmail发送电子邮件,

提问于
浏览
1

enter image description here
我使用python从gmail发送电子邮件 . 我打开gmail IMAP也获得了一个安全密码(一个16位密码) . 但是回复我的用户名和密码不被接受 . 我是谷歌帐户密码,端口25,587,465(使用ssl) . 不能工作 .

#! /usr/bin/python
# -*- coding: UTF-8 -*-

from email.mime.text import MIMEText
from email.header import Header
from email import encoders

import smtplib
sender = "Mygmail@gmail.com"
rec= "reciver@qq.com"
passwd = "security password"
#passwd = 'the really google account password'

message = MIMEText("邮件发送","plain","utf-8")
message['From'] =sender
message['To'] = rec
message['Subject'] =Header("from google","utf-8").encode()

smtpObj = smtplib.SMTP("smtp.gmail.com",587)
smtpObj.ehlo()                 
smtpObj.starttls()
smtpObj.set_debuglevel(1)
smtpObj.login(sender,passwd)
smtpObj.sendmail(sender,[rec],message.as_string)
smtpObj.close()

1 回答

  • 1

    试试以下内容,它过去对我有用

    #!/usr/bin/python
    
    #from smtplib import SMTP # Standard connection
    from smtplib import SMTP_SSL as SMTP #SSL connection
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText
    
    sender = 'example@gmail.com'
    receivers = ['example@gmail.com']
    
    
    msg = MIMEMultipart()
    msg['From'] = 'example@gmail.com'
    msg['To'] = 'example@gmail.com'
    msg['Subject'] = 'simple email via python test 1'
    message = 'This is the body of the email line 1\nLine 2\nEnd'
    msg.attach(MIMEText(message))
    
    ServerConnect = False
    try:
        smtp_server = SMTP('smtp.gmail.com','465')
        smtp_server.login('#name#@gmail.com', '#password#')
        ServerConnect = True
    except SMTPHeloError as e:
        print "Server did not reply"
    except SMTPAuthenticationError as e:
        print "Incorrect username/password combination"
    except SMTPException as e:
        print "Authentication failed"
    
    if ServerConnect == True:
        try:
            smtp_server.sendmail(sender, receivers, msg.as_string())
            print "Successfully sent email"
        except SMTPException as e:
            print "Error: unable to send email", e
        finally:
            smtp_server.close()
    

相关问题