Email 在Python3中从gmail发送emal

Email 在Python3中从gmail发送emal,email,python-3.x,Email,Python 3.x,我正在做我的第一个项目,在我的课本上阅读并编写了这个程序 import smtplib password=input(str("Enter your password for example@gmail.com") smtp0bj.ehlo() smtp0bj.starttls() smtp0bj.login('example@gmail.com',password) smtp0bj.sendmail('example@gmail.com','example2@gmail.com','examp

我正在做我的第一个项目,在我的课本上阅读并编写了这个程序

import smtplib
password=input(str("Enter your password for example@gmail.com")
smtp0bj.ehlo()
smtp0bj.starttls()
smtp0bj.login('example@gmail.com',password)
smtp0bj.sendmail('example@gmail.com','example2@gmail.com','example3@hotmail.com','subject:Testmail\nTesting,testing,1,2,3,testing'
{}
smtp0bj.quit()

根据我的课本,阿尔·斯维加特的《用Python自动化无聊的东西》,我是对的,但我一直收到一条错误消息。我做错什么了吗?还是我错过了一个重要的步骤?

你的问题之一似乎是程序开始时的语法错误:当你要求输入密码时,你打开了两组括号
input(str(
),然后只关闭一组,因此在末尾添加一个额外的括号应该可以解决这个问题

但是,您可以将
input(str(“text”)
替换为
input(“text”)
,因为您要做的是将字符串转换为字符串,这只是浪费时间,您可能要做的是将输入作为字符串获取(
str(input(“text”)
),这在本例中是不必要的,因为在python中输入会自动读取为字符串

另外,您似乎没有定义smtp0bj,我不确定您的名字是从哪里来的,因此,如果您再次阅读该教科书(我假设该名称来自教科书),可能会发现缺少一两行

如果您的代码不起作用,下面是一个程序的副本,我使用它通过python在Gmail中发送电子邮件:

from smtplib import SMTP_SSL as SMTP
import logging, logging.handlers, sys
from email.mime.text import MIMEText

try:
    logger = logging.getLogger("__main__")
    logger.setLevel(logging.DEBUG)
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    to=""                       #Recipient's email address
    frm=""                      #Sender's email address
    pswd=""                     #Sender's password
    sub=""                      #Subject of email
    text=""                     #Message to send
    msg = MIMEText(text, 'plain')
    msg['Subject'] = sub
    msg['To'] = to
except Exception as err:
    pass

try:
    conn = SMTP("smtp.gmail.com")
    conn.set_debuglevel(True)
    conn.login(frm, pswd)
    try: conn.sendmail(frm, to, msg.as_string())
    finally: conn.close()
except Exception as exc:
    print(exc)
    logger.error("ERROR!!!")
    logger.critical(exc)
    sys.exit("Mail failed: {}".format(exc))
希望这有帮助

编辑:

我在网上找到了你的书(),发现你错过了定义smtp服务器的步骤。添加行
smtpObj=smtplib.smtp('smtp.gmail.com',587)
将允许你从gmail发送电子邮件

import smtplib
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('MyEmailAddress@gmail.com', 'MyEmailPassword')
smtpObj.sendmail('MyEmailAddress@gmail.com', 'RecipientEmailAddress@example.com', 'Subject: SubjectText.\nMessage Text')
smtpObj.quit()

另外:请确保您的程序没有被称为
email.py
,因为tht是stmplib中使用的一个模块的名称,因此它将引发
AtributeError

欢迎使用Stack Overflow!要帮助人们回答您的问题,您需要比“我一直收到错误消息”更具体一些。请在帖子中加入准确的错误文本(最好使用复制+粘贴以避免转录错误)。