Azitech

Azimout's Linux weblog

Sending email from Python

leave a comment »

We distinguish three cases: no encryption/no authentication (port 25), TLS wrapper (port 465) and STARTTLS (port 587).

Port 25

import smtplib
srv = smtplib.SMTP(MAIL_SERVER)
srv.sendmail(from_addr=MAIL_FROM, to_addrs=MAIL_DEST, msg=my_msg)
srv.quit()

Port 465

import smtplib
srv = smtplib.SMTP_SSL(MAIL_SERVER, 465)
srv.login(MAIL_FROM, MAIL_PASSWD)
srv.sendmail(from_addr=MAIL_FROM, to_addrs=MAIL_DEST, msg=my_msg)
srv.quit()

Port 587

import smtplib
srv = smtplib.SMTP(MAIL_SERVER, 587)
srv.starttls()
srv.login(MAIL_FROM, MAIL_PASSWD)
srv.sendmail(from_addr=MAIL_FROM, to_addrs=MAIL_DEST, msg=my_msg)
srv.quit()

In all three cases, the message body should be structured like this:

my_msg = '\n'.join((
        "From: "+MAIL_FROM,
        "To: "+MAIL_DEST,
        "Subject: "+MAIL_SUBJECT,
        "",     # compulsory empty line between subject and body
        msg_body))

Further reading: http://docs.python.org/library/smtplib.html

Advertisements

Written by azimout

30/05/2011 at 15:19

Posted in Howto

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: