2. SMTP
Much like HTTP(Hyper-Text Transfer Protocol) is the protocol used
by computers to send web pages across the Internet.
Simple Mail Transfer Protocol(SMTP) is the protocol used to send
email.
SMTP dictates how emails should be:
Formatted
Encrypted
Relayed between mail servers
And all other details after you click send
There is a python library that allows you to invoke this protocol,
smtplib and another to retreive email but we will not get into that.
Code: import smtplib
3. SENDING EMAIL
There are 6 phases to sending an email message:
1. Connecting to the SMTP server
2. Greet the SMTP server to confirm the connection
3. Begin the TLS or SSL encryption
4. Pass user account credentials to the SMTP server to authenticate and login
5. Compose and send the email message
6. Close the connection
4. CONNECTING TO AN SMTP SERVER
If you have ever setup a 3rd party email software like Thunderbird, Outlook, or
you phone than you may be familiar with configuring the SMTP server and port.
These settings are different for each email provider but can be easily searched
for on the internet.
Ex.
Once you have the domain name and port information you can create the SMTP
connection. Port 25, 587 – TLS and 465 - SSL
Code: varName = smtplib.SMTP(serverDomain, port)
varName.ehlo()
Ex. smtpObj = smtplib.SMTP(“smtp.dtcc.edu”, 25)
smtpObj.ehlo()
Provider SMTP server Port
Gmail smtp.gmail.com 587
Hotmail smtp.gmail.com 587
DTCC smtp.dtcc.edu 25
5. LOGGING IN TO THE SERVER
First you will need to specify the encryption to pass your credentials
to the server.
For our purposes we will be using TLS encryption
Code: varName.starttls()
Once you establish the encryption, you can log into the SMTP server
with your username and password.
Code: varName.login(userName, password)
Ex.
smtpObj.starttls()
smtpObj.login(“myEmail@dtcc.edu”, “MyPassword”)
6. SENDING AN EMAIL
Once logged into the SMTP server you can use the sendmail() function
to actually send the email.
The sendmail() function requires 3 arguments:
Sender email address as a string (From:)
Recipient email address as a string (To:)
The email subject/body
The format of the body is “subject n body”. The new line separates the subject from the body, otherwise
everything is interpreted as the body of the email.
Code: varName.sendmail(senderEmail, RecipientEmail, Subject: n Body)
Ex. smtpObj.sendmail(“example@gmail.com”, “you@Hotmail.com”, “Subject: Test n This is the
body now Sincerely, Me”)
Finally, we want to disconnect from the SMTP server.
Code: varName.quit()
7. SENDING EMAIL EXAMPLE
import smtplib
smtpObj = smtplib.SMTP(“smtp.dtcc.edu”, 25)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(“myEmail@dtcc.edu”, “MyPassword”)
smtpObj.sendmail(“example@gmail.com”, “you@Hotmail.com”, “Subject: Test n This is the
body now Sincerely, Me”)
smtpObj.quit()