利用Python建立socket连接后发送假邮件

其实和telnet是一样的,用Python写只是为了方便反复测试

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

__author__ = 'tan9le'
from socket import *
#import ssl

smtp_server = "这里填写smtp服务器地址"
port  = 25
mailfrom = "需要伪装的发信者"
mailto = "真实的接受者"
Subject = "测试假邮件"
msgto = 'To: ' + mailto
msgfrom = 'From: ' + mailfrom
msgsubject = 'Subject: ' + Subject
msgcontent = '假邮件内容'
msgtype='Content-Type: text/plain;charset=UTF-8'

endmsg = '.'



clientSocket = socket(AF_INET, SOCK_STREAM)
#ssl_clientSocket = ssl.wrap_socket(clientSocket)
ssl_clientSocket = clientSocket
ssl_clientSocket.connect((smtp_server, port))
recv = ssl_clientSocket.recv(1024)
print
print recv

if recv[:3] != '220':
    print '220 reply not received from server.'

def sendMessage(message,code=None):
    ssl_clientSocket.send(message + '\r\n')
    if code:
        response = ssl_clientSocket.recv(1024)
        index = len(code)
        print response
        if response[:index] != code:
            print code + 'reply not received from server.'

#握手
sendMessage('HELO Python','250')


#请求认证
sendMessage('AUTH LOGIN','334')

#Base64编码后的用户名
sendMessage('用户全名Base64编码后填入','334')


#Base64编码后的密码
sendMessage('用户密码Base64编码后填入','235')


# 设置发信人
sendMessage('MAIL From: '+mailfrom,'250')

#设置收信人
sendMessage('RCPT To: '+mailto,'250')

#设置邮件内容
sendMessage('DATA','354')


# Send message data.
sendMessage(msgto)
sendMessage(msgfrom)
sendMessage(msgsubject)
sendMessage(msgtype)
sendMessage(msgcontent)


# 设置消息结束
sendMessage(endmsg)


#退出
sendMessage('QUIT','221')

标签: python, smtp