Skip to content

Instantly share code, notes, and snippets.

@smedegaard
Created February 20, 2014 10:33
Show Gist options
  • Save smedegaard/9110882 to your computer and use it in GitHub Desktop.
Save smedegaard/9110882 to your computer and use it in GitHub Desktop.
KTN NTNU smtp client
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import sys, ssl, base64, getpass
from socket import *
ssl.PROTOCOL_TLSv1
endmsg = '\r\n.\r\n'
# Choose a mail server (e.g. Google mail server) and call it mailserver
mailserver = "smtp.gmail.com"
port = 465
print ssl.get_server_certificate((mailserver, port))
username = raw_input('Gmail: ')
passw = getpass.getpass('password: ')
recipient = raw_input('Recipient email: ')
subject = raw_input('subject: ')
print 'Write a message. Send by hitting enter'
msg = '\r\n' + raw_input('Message: ')
# Create socket called clientSocket and establish a TCP connection with mailserver
#Fill in start
try:
clientSocket = socket(AF_INET, SOCK_STREAM)
except Exception, e:
print e
sslSock = ssl.wrap_socket(clientSocket)
try:
sslSock.connect((mailserver, port))
print sslSock.recv(1024)
except Exception, e:
print e
try:
sslSock.send('EHLO client\r\n')
print sslSock.recv(1024)
except Exception, e:
print e
try:
b64passw = base64.b64encode(passw)
b64username = base64.b64encode(username)
print b64username + ' > ' + b64passw
# authorization-id\0authentication-id\0passwd
x = base64.b64encode(username + '\0' + username + '\0' + passw)
sslSock.send('AUTH PLAIN ' + x + '\r\n')
print sslSock.recv(1024)
except Exception, e:
print e
# # # Send MAIL FROM command and print server response.
try:
sslSock.send('MAIL FROM: <' + username + '>\r\n')
print sslSock.recv(1024)
except Exception, e:
print e
# # # # Send RCPT TO command and print server response.
try:
sslSock.send('RCPT TO: <' + recipient + '>\r\n')
print sslSock.recv(1024)
except Exception,e:
print e
# # # # Send DATA command and print server response.
try:
sslSock.send('DATA\r\n')
print sslSock.recv(1024)
except Exception,e:
print e
# # # Send message data.
try:
sslSock.send('Subject: ' + subject + '\r\n' + msg + endmsg)
print sslSock.recv(1024)
except Exception,e:
print e
# # # Message ends with a single period.
# sslSock.send(endmsg)
# # # Send QUIT command and get server response.
try:
sslSock.send('QUIT\r\n')
print sslSock.recv(1024)
except Exception,e:
print e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment