domenica 29 maggio 2016

Python: inviare una email usando un server SMTP

Una raccolta di piccoli esempi di codice per inviare email usando Python e SMTP. Il server smtp può essere quello del vostro fornitore di posta elettronica, ad esempio Libero.


Inviare email con Python 3.3 o superiori, server SMTP e autenticazione TLS

# Send email with SMTP and TLS example with Python 3.3 or above
import smtplib
FROM = "example@example.com"
TO = ["example@example.com"] # must be a list
SUBJECT = "Email from Python program"
TEXT = "This is a message from Python programm."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
with smtplib.SMTP('smtp.example.com', 587) as server:
server.set_debuglevel(1) # for debug, unnecessary
server.starttls()
server.login('example@example.com', 'example_password')
server.sendmail(FROM, TO, message)


Inviare email con Python 3.2 o inferiori, server SMTP e autenticazione TLS

# Send email with SMTP and TLS example with Python 3.2 and lower
import smtplib
FROM = "example@example.com"
TO = ["example@example.com"] # must be a list
SUBJECT = "Email from Python program"
TEXT = "This is a message from Python programm."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP('smtp.example.com', 587)
server.set_debuglevel(1) # for debug, unnecessary
server.starttls()
server.login('example@example.com', 'example_password')
server.sendmail(FROM, TO, message)
server.quit()

1 commento:

L'autore del commento si assume la totale responsabilità del suo contenuto. Commenti ritenuti offensivi o non attinenti potranno essere cancellati.