WEB DEVELOPER SITE
PHP7
 

Python Sending Email using SMTP


Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers.


import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Operater Description
host host running STMP server Ip address or domain name such as welookups.com
port port STMP server is listening. Usually this port would be 20
local_hostname SMTP server is run on local machine.

Example

Here the simple example example of STMP you can study



#!/usr/bin/python

import smtplib

sender = 'from@school.com'
receivers = ['to@school.com']

message = """From: From Person 
To: To Person 
Subject: SMTP e-mail test
In this sample website
"""
try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print "sucessful sent email"
except SMTPException:
   print "Error: unable to access"

Note: Here

Sending Attachments to email

Example

#!/usr/bin/python

import smtplib
import base64

filename = "/tmp/demo.txt"


# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent)  # base64

sender = 'webmaster@welookups.com'
reciever = 'amrood.admin@gmail.com'

cheker = "AFTER"

body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person 
To: To Person 
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (checker, checker)


# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body,checker)




# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s

%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, reciever, message)
   print "Successfully sent email"
except Exception:
   print "Error: unable to send email"