Sending mail via SMTP in Python
SMTP (Simple Mail Transfer Protocol) is the most common protocol for sending mail. The communication in SMTP is done using TCP.
Read more about the SMTP protocol here: RFC821
Here’s an example of a simple Python program that sends a mail.
Send mail in Python using SMTP
import smtplib
addr_from = “from@mail.domain”
addr_to = “to@mail.domain”server=smtplib.SMTP(‘smtp.server.domain’)
server.set_debuglevel(1)msg = (“From: %s\r\nTo: %s\r\n\r\n”
% (addr_from, “, “.join(addr_to)))msg = msg + “This is the message”
server.sendmail(addr_from, addr_to, msg)
server.quit()
‘smtp.server.domain’ specifies the SMTP server the program is going to use. You can experiment with different free SMTP servers until you find something that works. Personally, I use my ISP SMTP server.
smtplib is the module I used in order to use SMTP in Python. Information about smtplib can be found in the official Python documentation here.
5 Responses
Subscribe to comments with RSS.
Most smtp server has password authentication. Do you know how do I enable it from smtplib?
Invoke the login method of the server object after you connect to the SMTP-server.
server=smtplib.SMTP("smtp.server.domain") # connect
server.login("username","password") # login
Good script. Very useful.
Thanks, this allowed me to send mail notifications through mdadm. 😀
Is there any way to easily add an attachment to the mail?
-Thanks
what if i want to add an attachment?