Python send mail to multiple recipients using SMTP server
In this post, you will learn how to write Python code to send email to multiple recipients. For sending mail, we will use the SMTP server.
SMTP (Simple Mail Transfer Protocol) is a TCP/IP protocol of the internet standard for electronic mail transmission from sender to one or more recipients. To connect to SMTP mail server, we need details HOSTNAME, USERNAME, PASSWORD and PORT NUMBER.
Python provides in-built module smtplib to send email using SMTP Server. There is no extra installation required. So first, we need to import this at the top of the script and define a SMTP client session object that can be used to send mail.
Python Connect to SMTP Server
The SMTP object encapsulates a SMTP connection. It has the following syntax -
smtplib.SMTP([host, port, local_hostname, timeout)
host - The host name of your SMTP server. We can specify the IP address of the host or a domain name.
port - The port number where the SMTP server is listening. Generally, this port would be 25.
local_hostname - If your STMP server is running on the local machine, then we can just specify the 'localhost'.
timeout - It is an optional parameter and specifies a timeout in seconds for blocking operations.
STMP Authentication requires login to the SMTP Server. It has the following syntax -
The arguments are the username and password to authenticate with the server.
We should start the TLS for a security reason. It will encrypt all the commands following this.
The sendmail() function is used to send mail to the recipients. It has the following syntax -
sendmail(from, to, msg)
Here, the from is the sender mail address and the to is the recipient mail address, the msg contains messages to be sent in the string.
Quit the SMTP connection
At last, we should terminate the SMTP session and close the connection using SMTP QUIT() command.
Python code to send mail
Here is the complete code in Python to send mail to multiple recipients using SMTP Mail Server.
Related ArticlesPython NumPy: Overview and Examples
Convert Python list to numpy array
numpy dot product
Python Pandas Plotting
Pandas string to datetime
Convert Excel to CSV Python Pandas
Python take screenshot of specific window
Read data from excel file using Python Pandas
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml