Domanda

Sono nuovo con Python .. In realtà, sto cercando di inviare e-mail in primo piano con Python: corpo html, corpo alternativo del testo e allegato.

Quindi, ho trovato questo tutorial e adattato con l'autenticazione gmail (tutorial trovato qui )

Il codice che ho atm è questo:

def createhtmlmail (html, text, subject):
"""Create a mime-message that will render HTML in popular
  MUAs, text in better ones"""
import MimeWriter
import mimetools
import cStringIO
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os

out = cStringIO.StringIO() # output buffer for our message 
htmlin = cStringIO.StringIO(html)
txtin = cStringIO.StringIO(text)

writer = MimeWriter.MimeWriter(out)
#
# set up some basic headers... we put subject here
# because smtplib.sendmail expects it to be in the
# message body
#
writer.addheader("Subject", subject)
writer.addheader("MIME-Version", "1.0")
#
# start the multipart section of the message
# multipart/alternative seems to work better
# on some MUAs than multipart/mixed
#
writer.startmultipartbody("alternative")
writer.flushheaders()
#
# the plain text section
#
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
mimetools.encode(txtin, pout, 'quoted-printable')
txtin.close()
#
# start the html subpart of the message
#
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
#
# returns us a file-ish object we can write to
#
pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
mimetools.encode(htmlin, pout, 'quoted-printable')
htmlin.close()


#
# Now that we're done, close our writer and
# return the message body
#
writer.lastpart()
msg = out.getvalue()
out.close()
return msg

import smtplib
f = open("/path/to/html/version.html", 'r')
html = f.read()
f.close()
f = open("/path/to/txt/version.txt", 'r')
text = f.read()
subject = "Prova email html da python, con allegato!"
message = createhtmlmail(html, text, subject)
gmail_user = "thegmailaccount@gmail.com"
gmail_pwd = "thegmailpassword"
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(gmail_user, gmail_pwd)
server.sendmail(gmail_user, "example@example.com", message)
server.close()

e funziona .. ora manca solo l'allegato .. E non sono in grado di aggiungere l'allegato (da questo post )

Quindi, perché non esiste una classe Python come phpMailer per php? È perché, per un programmatore python di media capacità, l'invio di un'e-mail html con allegato e testo alternativo è così semplice che non è necessaria una lezione? O è perché non l'ho trovato?

Se potessi scrivere una lezione del genere, quando sarò abbastanza bravo con Python, sarebbe utile per qualcuno?

È stato utile?

Soluzione

Se puoi scusare qualche palese autopromozione, ho scritto un modulo mailer che rende l'invio di e-mail con Python abbastanza semplice. Nessuna dipendenza oltre alle librerie e-mail Python smtplib.

Ecco un semplice esempio per inviare un'e-mail con un allegato:

from mailer import Mailer
from mailer import Message

message = Message(From="me@example.com",
                  To=["you@example.com", "him@example.com"])
message.Subject = "Kitty with dynamite"
message.Body = """Kitty go boom!"""
message.attach("kitty.jpg")

sender = Mailer('smtp.example.com')
sender.login("username", "password")
sender.send(message)

Modifica : ecco un esempio di invio di un'email HTML con testo alternativo. :)

from mailer import Mailer
from mailer import Message

message = Message(From="me@example.com",
                  To="you@example.com",
                  charset="utf-8")
message.Subject = "An HTML Email"
message.Html = """This email uses <strong>HTML</strong>!"""
message.Body = """This is alternate text."""

sender = Mailer('smtp.example.com')
sender.send(message)

Modifica 2 : grazie a uno dei commenti, ho aggiunto una nuova versione di mailer a pypi che ti consente di specificare la porta nella classe Mailer.

Altri suggerimenti

Django include la classe di cui hai bisogno nel core, documenti qui

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.attach_file('/path/to/file.jpg')
msg.send()

Nelle mie impostazioni ho:

#GMAIL STUFF
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'name@gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587

Voglio solo indicare Progetto Lamson che era quello che stavo cercando quando ho trovato questa discussione. Ho fatto qualche altra ricerca e l'ho trovato. E ':

  

L'obiettivo di Lamson è quello di porre fine all'inferno che è lo "sviluppo di applicazioni e-mail". Invece di rimanere bloccato negli anni '70, Lamson adotta il moderno design del framework di applicazioni Web e utilizza un linguaggio di scripting collaudato (Python).

Si integra perfettamente con Django. Ma è più realizzato per applicazioni basate su e-mail. Sembra però puro amore.

Forse puoi provare con turbomail python-turbomail.org

È più facile e utile :)

import turbomail

# ...

message = turbomail.Message("from@example.com", "to@example.com", subject)
message.plain = "Hello world!"

turbomail.enqueue(message)

Consiglio di leggere il SMTP rfc . Una ricerca su Google mostra che questo può essere fatto facilmente usando la classe MimeMultipart che stai importando ma che non usi mai. Ecco alcuni esempi sul sito di documentazione di Python.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top