Fix Python – Sending mail from Python using SMTP


Asked By – Eli Bendersky

I’m using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I’m missing ?

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)

Now we will see solution for issue: Sending mail from Python using SMTP


The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.

I rely on my ISP to add the date time header.

My ISP requires me to use a secure smtp connection to send mail, I rely on the smtplib module (downloadable at

As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.


#! /usr/local/bin/python

SMTPserver = ''
sender =     ''
destination = ['']


# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'

Test message

subject="Sent from Python"

import sys
import os
import re

from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)

# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText

    msg = MIMEText(content, text_subtype)
    msg['Subject']=       subject
    msg['From']   = sender # some SMTP servers will do this automatically, not all

    conn = SMTP(SMTPserver)
    conn.login(USERNAME, PASSWORD)
        conn.sendmail(sender, destination, msg.as_string())

    sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message

This question is answered By – Vincent Marchetti

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0