Skip to content. | Skip to navigation

Personal tools
Log in
Sections
You are here: Home Web Plone Snippets and Examples Sending HTML Email

Sending HTML Email

Thanks to Web Collective for this one
# Send an HTML email with an embedded image and a plain text message for
# email clients that don't want to display the HTML.

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from Products.Archetypes.debug import log


def sendHTMLEmail(self, subject, strFrom, strTo, html_message, plaintext_message): 
  # Define these once; use them twice!
  
  # Create the root message and fill in the from, to, and subject headers
  msgRoot = MIMEMultipart('related')
  msgRoot['Subject'] = subject
  msgRoot['From'] = strFrom
  msgRoot['To'] = strTo
  msgRoot.preamble = 'This is a multi-part message in MIME format.'
  
  # Encapsulate the plain and HTML versions of the message body in an
  # 'alternative' part, so message agents can decide which they want to display.
  msgAlternative = MIMEMultipart('alternative')
  msgRoot.attach(msgAlternative)
  
  msgText = MIMEText(plaintext_message)
  msgAlternative.attach(msgText)
  
  # We reference the image in the IMG SRC attribute by the ID we give it below
  msgText = MIMEText(html_message, 'html')
  msgAlternative.attach(msgText)
  
  #### This example assumes the image is in the current directory
  #fp = open('test.jpg', 'rb')
  #msgImage = MIMEImage(fp.read())
  #fp.close()
  
  # Define the image's ID as referenced above
  #msgImage.add_header('Content-ID', '<image1>')
  #msgRoot.attach(msgImage)
  
  # Send the email (this example assumes SMTP authentication is required)
  log ("starting to email")
  import smtplib
  log ("imported smtplib")
  smtp = smtplib.SMTP()
  log ("created smtplib object")
  smtp.connect('localhost')
  log ("connected to local host via smtplib ")
  smtp.sendmail(strFrom, [strTo], msgRoot.as_string())
  log ("executed sendmail")
  smtp.quit()
  log ("successfully emailed")
  log (msgRoot.as_string() )
  return

Document Actions

Comments (0)

« May 2012 »
May
MoTuWeThFrSaSu
123456
78910111213
14151617181920
21222324252627
28293031