Professional Documents
Culture Documents
Unit-5 (1)
Unit-5 (1)
Unit-5 (1)
Simple Mail Transfer Protocol (SMTP) is used as a protocol to handle the email transfer
using Python. It is used to route emails between email servers. It is an application layer
protocol which allows to users to send mail to another. The receiver retrieves email
using the protocols POP(Post Office Protocol) and IMAP(Internet Message Access
Protocol).
When the server listens for the TCP connection from a client, it initiates a connection
on port 587.
Python provides a smtplib module, which defines the SMTP client session object used
to send emails to an internet machine.
To Install SMTPLib
For this purpose, we have to import the smtplib module using the import statement.
1. import smtplib
The SMTP object is used for the email transfer. The following syntax is used to create
the smtplib object.
1. import smtplib
2. smtpObj = smtplib.SMTP(host, port, local_hostname)
Here are four basic steps for sending emails using Python:
2) Create the MIMEMultipart message object and load it with appropriate headers
for From, To, and Subject fields.
3) Add your message body.
Or
Step 2: After that create a session, we will be using its instance SMTP to encapsulate an SMTP
connection.
s = smtplib.SMTP('smtp.gmail.com', 587)
Step 3: In this, you need to pass the first parameter of the server location and the second
parameter of the port to use. For Gmail, we use port number 587.
Step 4: For security reasons, now put the SMTP connection in TLS mode. TLS (Transport Layer
Security) encrypts all the SMTP commands. After that, for security and authentication, you
need to pass your Gmail account credentials in the login instance. The compiler will show an
authentication error if you enter an invalid email id or password.
Step 5: Store the message you need to send in a variable say, message. Using the sendmail()
instance, send your message. sendmail() uses three parameters: sender_email_id,
receiver_email_id and message_to_be_sent. The parameters need to be in the same
sequence.
The sendmail() method of the SMTP object is used to send the mail to the desired
machine. The syntax is given below.
Example
import smtplib
sender_mail = 'sender@fromdomain.com'
receivers_mail = ['reciever@todomain.com']
message = """From: From Person %s
To: To Person %s
Subject: Sending SMTP e-mail
This is a test e-mail message.
"""% (sender_mail, receivers_mail)
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender_mail, receivers_mail, message)
print("Successfully sent email")
except Exception as e:
print("Error: unable to send email", e)
%s operator in python
We can use the %s operator to append the given string variable inside a string by
putting it where we want to add the value. Python will simply add the string variables
where we have used the %s operator in the string. Let's go through an example to
understand it.
str1 = "MCA"
str2 = "Python Class"
str3 = "good"
# Appending multiple string values inside a single string
print("Hello %s, Welcome to the %s! I hope you all are %s." % (str1, str2, str3))
This will send the email from your account. After you have completed your task, terminate
the SMTP session by using quit().
Starting a Secure SMTP Connection
When you send emails through Python, you should make sure that your SMTP
connection is encrypted, so that your message and login credentials are not
easily accessed by others. SSL (Secure Sockets Layer) and TLS (Transport
Layer Security) are two protocols that can be used to encrypt an SMTP
connection. It’s not necessary to use either of these when using a local debugging
server.
There are two ways to start a secure connection with your email server:
import smtplib
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login("sender_email_id", "sender_email_id_password")
# message to be sent
message = "Message_you_need_to_send"
# sending the mail
s.sendmail("sender_email_id", "receiver_email_id", message)
# terminating the session
s.quit()
Code Example
The following code example lets you send personalized emails to multiple
contacts. It loops over a CSV file with name,email,grade for each contact, as in
the example above.
The general message is defined in the beginning of the script, and for each contact
in the CSV file its {name} and {grade} placeholders are filled in, and a
personalized email is sent out through a secure connection with the Gmail server,
as you saw before:
context = ssl.create_default_context()
with smtplib. SMTP_SSL ("smtp.gmail.com", 465, context=context) as server:
server.login(from_address, password)
with open("contacts_file.csv") as file:
reader = csv.reader(file)
next(reader) # Skip header row
for name, email, grade in reader:
server.sendmail(
from_address,
email,
message.format(name=name, grade=grade),
)
Email List File (emails.csv):
Create a CSV file named emails.csv with at least two columns: one for the recipient's email
address and optionally other columns for personalized information like the recipient's name.
csv
email,name
recipient1@example.com,John
recipient2@example.com,Alice
recipient3@example.com,Bob
Python Script:
Write a Python script to read the CSV file, extract the email addresses and other personalized
information, and send personalized marketing emails to each recipient.
python
import csv
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# Email configuration
sender_email = 'your_email@example.com'
password = 'your_password'
This script will read the email addresses and other information from the CSV file, personalize
the email message for each recipient, and send the emails using your SMTP server. Make sure
to test with a small list of emails first to ensure everything is working as expected before
sending to a larger list. Additionally, be sure to comply with relevant laws and regulations
regarding email marketing and privacy.