Unit-5 (1)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Python Sending Email using SMTP

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

pip 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)

It accepts the following parameters.


o host: It is the hostname of the machine which is running your SMTP server. Here, we
can specify the IP address of the server like (https://www.internet.com) or localhost. It
is an optional parameter.
o port: It is the port number on which the host machine is listening to the SMTP
connections. It is 25 by default.
o local_hostname: If the SMTP server is running on your local machine, we can mention
the hostname of the local machine.

Here are four basic steps for sending emails using Python:

1) Set up the SMTP server and log into your account.

2) Create the MIMEMultipart message object and load it with appropriate headers
for From, To, and Subject fields.
3) Add your message body.

4) Send the message using the SMTP server object.

Or

Step 1: First of all, “smtplib” library needs to be imported.

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.

1. smtpObj.sendmail(sender, receiver, message)

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.

Example: Look at the following code:

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:

 Start an SMTP connection that is secured from the beginning using


SMTP_SSL().
 Start an unsecured SMTP connection that can then be encrypted using.
starttls().

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()

Send Email to Multiple Recipients using Python


If you need to send the same message to different people. You can use for loop
for that. For example, you have a list of email ids to which you need to send the
same mail. To do so, insert a “for” loop between the initialization and termination
of the SMTP session. Loop will initialize turn by turn and after sending the email,
the SMTP session will be terminated.
import smtplib

# list of email_id to send the mail


li = ["xxxxx@gmail.com", "yyyyy@gmail.com"]

for dest in li:


s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login("sender_email_id", "sender_email_id_password")
message = "Message_you_need_to_send"
s.sendmail("sender_email_id", dest, message)
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:

import csv, smtplib, ssl

message = """Subject: Your grade

Hi {name}, your grade is {grade}"""


from_address = "my@gmail.com"
password = input("Type your password and press enter: ")

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'

# Read emails from CSV file


with open('emails.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
receiver_email = row['email']
name = row.get('name', '') # Get name if available, or empty string

# Create personalized message


message = MIMEMultipart()
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = 'Personalized Marketing Email'

body = f'Hi {name},\n\nThis is a personalized marketing email sent to


{receiver_email}.\n\nBest regards,\nYour Company'
message.attach(MIMEText(body, 'plain'))

# Connect to SMTP server and send email


with smtplib.SMTP('smtp.example.com', 587) as server: # Replace with your SMTP
server
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
print(f"Email sent to {receiver_email}")
Replace 'your_email@example.com' and 'your_password' with your email credentials. Also,
replace 'smtp.example.com' with the address of your SMTP server.

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.

You might also like