Python send mail to multiple recipients using SMTP server
SMTP (Simple Mail Transfer Protocol) is a TCP/IP protocol of 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.
To send email using SMTP Server in Python, we are using smtplib library. So first, we need to import this at the top of script using -
Connect to SMTP Server
The SMTP object encapsulates an SMTP connection. It has the following syntax -
smtplib.SMTP([host, port, local_hostname, timeout)
host - The host name running your SMTP server.
port - The port number where the SMTP server is listening.
local_hostname - If your STMP server is running on the local machine, then only specify 'localhost'.
timeout - It is an optional parameter and specifies 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 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, from is the sender mail address and to is the recipient mail address, msg contains messages to be send in 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 to send mail to multiple recipients using SMTP Mail Server.
Related ArticlesHow 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