Patrick’s development blog

Sending mail via SMTP in Python

Posted in Python by Patrick on June 22, 2008

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.

Advertisements

5 Responses

Subscribe to comments with RSS.

  1. Sebastian Bassi said, on June 26, 2008 at 3:33 am

    Most smtp server has password authentication. Do you know how do I enable it from smtplib?

  2. patrickbe said, on June 26, 2008 at 10:46 am

    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

  3. Posicionamiento Valencia said, on October 7, 2008 at 9:43 pm

    Good script. Very useful.

  4. Lars Dongrie Oppholdsnes said, on February 19, 2009 at 5:05 pm

    Thanks, this allowed me to send mail notifications through mdadm. 😀

    Is there any way to easily add an attachment to the mail?

    -Thanks

  5. xishan said, on November 19, 2009 at 5:33 am

    what if i want to add an attachment?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: