使用Python自动登录Gmail

问题描述 投票:-1回答:3

我正在编写一个可以登录Gmail的Python程序。

此程序的目的是检查用户名/密码组合是否存在且是否正确。

由于此程序用于测试用户名/密码组合的存在,因此无需知道Gmail中的任何邮件内容。

该程序的输入是用户名和密码。

该程序的输出是

成功登录

要么

登录失败

登录失败可能是:

  1. 现有用户名+错误密码
  2. 不存在的用户名

我的想法是先登录Gmail。之后,当登录失败时,gmail网页将在登录网页上显示特定消息。我可以解析网页内容并检查它是否有该特定消息。

但是,我仍然不知道如何在Python中登录Gmail。请告诉我可以使用哪个模块或者给我一小段示例代码。

python gmail
3个回答
-1
投票

这种事情就像被禁止一样,这就是创建OAuth或OpenID之类的原因。这种东西允许用户登录而无需输入用户名和密码。所以要小心。


2
投票

这是一个想法:

为什么不尝试从帐户发送电子邮件,看看它是否发送?您可以在python标准模块中使用smtplib执行此操作。有代码示例here。您将不得不查看模块的文档,但如果登录失败,它看起来像是一个异常,它应包含您感兴趣的详细信息。

在编辑中:

我挖出了这些代码,我写的就是这样做的。你需要在底部的位置放置一个try/catch来检测错误的登录凭据。

# Subject
now = dt.datetime.now().ctime()
subject = 'Change to system on %s' % now

# Body
body = 'Subject: %s,\n' % subject
body += 'On %s, a change to the system was detected. Details follow.\n\n' % now

relevantFiles = list(set([x.file for x in relevantChunks]))
for file in relevantFiles:

    fileChunks = [x for x in relevantChunks if x.file == file]
    for chunk in fileChunks:
        body += '****** Affected file %s. ' % chunk.file
        <some other stuff>

server = smtp.SMTP(args.host) # host = smtp.gmail.com:<port> look this bit up
server.starttls()
server.login(args.username, args.password)
server.sendmail(args.sender, args.recipient, body)
server.quit()

顺便说一句,我不太清楚为什么这个问题被低估了,甚至不知道除了你提出错误的问题之外还要投票。


0
投票

试试这个:

from email.mime.text import MIMEText
import smtplib

msg = MIMEText("Hello There!")

msg['Subject'] = 'A Test Message'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'

s = smtplib.SMTP('smtp.gmail.com:587')
s.starttls()  ##Must start TLS session to port 587 on the gmail server
s.login('username', 'passsword') ##Must pass args gmail username & password in quotes to authenticate on gmail
s.sendmail('[email protected]',['[email protected]'],msg.as_string())

print("Message Sent")
© www.soinside.com 2019 - 2024. All rights reserved.