Sending mail from Python with SMTP

September 10th, 2008 at 8:21 pm

Just a short notice to show how simple it is to send mail from Python using the SMTP module. Note: you must have an accessible SMTP server running somewhere. I have one on my domain, but word on the street says that if you ask nicely, your ISP can provide you with one.

Anyway, here is the code:

from smtplib import SMTP
import datetime

debuglevel = 0

smtp = SMTP()
smtp.connect('YOUR.MAIL.SERVER', 26)

from_addr = "John Doe <>"
to_addr = ""

subj = "hello"
date = "%d/%m/%Y %H:%M" )

message_text = "Hello\\nThis is a mail from your server\\n\\nBye\\n"

msg = "From: %s\\nTo: %s\\nSubject: %s\\nDate: %s\\n\\n%s" \
        % ( from_addr, to_addr, subj, date, message_text )

smtp.sendmail(from_addr, to_addr, msg)

Some notes:

  • You’ll have to insert your mail server and SMTP port. Note that the port can also be 25 (or any other, if you’ve configured the server appropriately)
  • At least on my server, the username must be the full email address
  • The message must contain all these fields to be accepted
  • Set debuglevel to 1 to see lots of insightful debugging information from the module

Related posts:

  1. Local execution of Python CGI scripts – with Python 3
  2. Local execution of Python CGI scripts
  3. Installing Python 2.5 on Bluehost
  4. Listing all serial ports on Windows with Python
  5. gmail

4 Responses to “Sending mail from Python with SMTP”

  1. MichaelNo Gravatar Says:

    In the ‘msg=’ line formatting screwed up the slashes

  2. elibenNo Gravatar Says:

    Fixed, thanks!

  3. Mats TaraldsvikNo Gravatar Says:

    Yeah, this Python-module is brilliant!

    I use it with filters in evolution :

    “Mail from forum”

    with this script is piped to the python script (regex + sends a new mail) and the above mail is deleted. New mail :

    “New post in ”

    And hence solves forums with not-very-descriptive subject lines in their automatic e-mails.

  4. TonyNo Gravatar Says:

    Great module information by setting debuglevel to 1. I wasn’t even aware that was available. Thanks.