以下是我当前在端口 587 上连接到 gmail 的 smtp 服务器的代码。发出 STARTTLS 命令后,我如何完成 TLS 会话协商并开始发出 AUTH LOGIN 和 MAIL FROM 等命令?我省略了 Base64 编码的 gmail 用户名,并将其替换为代码底部附近的 xxxxxxxx。
我从这个程序中得到的输出是:
220 mx.google.com ESMTP y10sm3296641yhd.6
250-mx.google.com 为您服务,[75.66.47.144]
250-尺寸 35882577
250-8位MIME
250-STARTTLS
250 个增强状态代码
220 2.0.0 准备启动 TLS
from socket import *
import ssl
msg = "\r\n smtp.."
endmsg = "\r\n.\r\n"
# Mailserver hostname and port to be used.
mailserver = ("smtp.gmail.com", 587)
# Create a socket and create an active TCP connection with the mailserver
clientSocket = socket(AF_INET, SOCK_STREAM);
clientSocket.connect(mailserver)
# Read server response
recv = clientSocket.recv(1024)
print recv
if recv[:3] != '220':
print '220 reply not received from server.'
# Send EHLO command and print server response.
ehloCommand = 'EHLO smtp.google.com\r\n'
clientSocket.send(ehloCommand)
recv1 = clientSocket.recv(1024)
print recv1
if recv1[:3] != '250':
print '250 reply not received from server.'
# Send STARTTLS command to server and print server response
command = "STARTTLS\r\n"
clientSocket.send(command)
recv1 = clientSocket.recv(1024)
print recv1
if recv[:3] != '220':
print '220 reply not received from server.'
# SEND AUTH LOGIN command and Base64 encoded username
command = "AUTH LOGIN xxxxxxxxxxxxx\r\n"
clientSocket.send(command)
recv1 = clientSocket.recv(1024)
print recv1
您可以 ssl 包装连接的套接字。这会给你这样的想法:
import ssl
import base64
from socket import *
cc = socket(AF_INET, SOCK_STREAM)
cc.connect(("smtp.gmail.com", 587))
# cc.read(..)
cc.send('helo tester.com\r\n')
cc.send('starttls\r\n')
# cc.read(..) If the server responds ok to starttls
# tls negotiation needs to happen and all
# communication is then over the SSL socket
scc = ssl.wrap_socket(cc, ssl_version=ssl.PROTOCOL_SSLv23)
scc.send('auth login\r\n')
# scc.read(..)
scc.send(base64.b64encode('username')+'\r\n')
scc.send(base64.b64encode('password')+'\r\n')
# css.send(
# mail from:
# rcpt to:
# data
# etc
查看此页面的“身份验证登录”部分,了解有关用户名/密码编码的信息:http://www.samlogic.net/articles/smtp-commands-reference-auth.htm
将 AUTH LOGIN 命令发送到服务器后,
服务器通过发送 BASE64 编码文本询问用户名和密码
(问题)给客户。 “VXNlcm5hbWU6”是BASE64编码文本
对于单词“用户名”和“UGFzc3dvcmQ6”是 BASE64 编码文本
对于上例中的“密码”一词。客户端发送
用户名和密码也使用 BASE64 编码。 “adlxdkej”,在
上面的示例是 BASE64 编码的用户名,“lkujsefxlj”是
BASE64 编码的密码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)