views:

626

answers:

5

Hi guys, i'm new with python.. Actually, i'm trying to send featured email with python: html body, text alternative body, and attachment.

So, i've found this tutorial and adapted it with the gmail authentication (tutorial found here)

The code i have atm, is that:

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 = "[email protected]"
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, "[email protected]", message)
server.close()

and that works.. now only miss the attachment.. And i am not able to add the attachment (from this post)

So, why there is not a python class like phpMailer for php? Is it because, for a medium-able python programmer sending a html email with attachment and alt text body is so easy that a class is not needed? Or is because i just didn't find it?

If i'll be able to wrote a class like that, when i'll be enough good with python, would that be useful for someone?

A: 

I recommend reading the SMTP rfc. A google search shows that this can easily be done by using the MimeMultipart class which you are importing but never using. Here are some examples on Python's documentation site.

apphacker
Yes, i swear i'll give a read.What about the question that a email class doesnt exist yet?I i'll wrote one, spitting litres of blood, would be usefull for someone, or noone will use it becose python programmer 'just use the procedural approach'? (im just guessing ah)
DaNieL
You might want to use something like Django that provides this for you.
apphacker
+1  A: 

Django includes the class you need in core, docs here

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', '[email protected]', '[email protected]'
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()

In my settings I have:

#GMAIL STUFF
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
YHVH
That's what i was looking for!Thanks mate.Last thing: to use that class we must download and install django, obvisiuly..Cold be fine a class that run without the django framework, but just running the class file (and the natural python modules))
DaNieL
+4  A: 

If you can excuse some blatant self promotion, I wrote a mailer module that makes sending email with Python fairly simple. No dependencies other than the Python smtplib and email libraries.

Here's a simple example for sending an email with an attachment:

from mailer import Mailer
from mailer import Message

message = Message(From="[email protected]",
                  To=["[email protected]", "[email protected]"])
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)

Edit: Here's an example of sending an HTML email with alternate text. :)

from mailer import Mailer
from mailer import Message

message = Message(From="[email protected]",
                  To="[email protected]",
                  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)

Edit 2: Thanks to one of the comments, I've added a new version of mailer to pypi that lets you specify the port in the Mailer class.

Ryan Ginstrom
add in an example of alternate text and you've got a winner!
YHVH
Wow, that's great!Does your module allow send mail througt the Gmail smtp?Where should i specify the smtp port (such as server = smtplib.SMTP("smtp.gmail.com", 587) with smtplib)
DaNieL
@DaNiel:Very good point, thanks. I've added an updated version that lets you specify the port in the Mailer class (`sender = Mailer('localhost', port=587)') http://pypi.python.org/pypi/mailer/0.4
Ryan Ginstrom
Hi Ryan, i tried the 0.4 version with gmail but it raise an error: File "C:\Python26\lib\smtplib.py", line 522, in login raise SMTPException("SMTP AUTH extension not supported by the server")Maybe its becose gmail requires the TLS?
DaNieL
A: 

Maybe you can try with turbomail python-turbomail.org

It's more easy and useful :)

import turbomail

# ...

message = turbomail.Message("[email protected]", "[email protected]", subject)
message.plain = "Hello world!"

turbomail.enqueue(message)
julionc
A: 

Just want to point to Lamson Project which was what I was looking for when I found this thread. I did some more searching and found it. It's:

Lamson's goal is to put an end to the hell that is "e-mail application development". Rather than stay stuck in the 1970s, Lamson adopts modern web application framework design and uses a proven scripting language (Python).

It integrates nicely with Django. But it's more made for email based applications. It looks like pure love though.

Velmont
i'll give it a try ;)
DaNieL