sam
sam

Reputation: 203

how to send an html file as an email in python?

import fnmatch
import os
import lxml.html
import smtplib
import sys

matches = []
for root, dirnames, filenames in os.walk('C:\AUDI\New folder'):
    for filename in fnmatch.filter(filenames, '*.html'):
        matches.append(os.path.join(root, filename))
    print filename

    page = filename  #the webpage to send

    root = lxml.html.parse(page).getroot()
    root.make_links_absolute()

    content = lxml.html.tostring(root)

    message = """From: sam <[email protected]>
    To: sam <[email protected]>
    MIME-Version: 1.0
    Content-type: text/html
    Subject: %s

    %s""" %(page, content)


    smtpserver = smtplib.SMTP("smtp.gmail.com",587)
    smtpserver.starttls()
    smtpserver.login("[email protected]",os.environ["GPASS"])
    smtpserver.sendmail('[email protected]', ['[email protected]'], message)

In the above code : Firstly, I am finding the *.html files in a directory. I am finding it, it is working fine for me. Later I want to send that html file as an email to some person. I am failing in that. Can someone suggest me how to do that ? print filename : is printing the list of html file in the directory, I have problem in sending the file as email. I am getting the error as :

File ".\task.py", line 15, in <module>
    root = lxml.html.parse(page).getroot()
  File "C:\Python27_3\lib\site-packages\lxml\html\__init__.py", line 789, in parse
    return etree.parse(filename_or_url, parser, base_url=base_url, **kw)
  File "lxml.etree.pyx", line 3310, in lxml.etree.parse (src\lxml\lxml.etree.c:72517)
  File "parser.pxi", line 1791, in lxml.etree._parseDocument (src\lxml\lxml.etree.c:105979)
  File "parser.pxi", line 1817, in lxml.etree._parseDocumentFromURL (src\lxml\lxml.etree.c:106278)
  File "parser.pxi", line 1721, in lxml.etree._parseDocFromFile (src\lxml\lxml.etree.c:105277)
  File "parser.pxi", line 1122, in lxml.etree._BaseParser._parseDocFromFile (src\lxml\lxml.etree.c:100227)
  File "parser.pxi", line 580, in lxml.etree._ParserContext._handleParseResultDoc (src\lxml\lxml.etree.c:94350)
  File "parser.pxi", line 690, in lxml.etree._handleParseResult (src\lxml\lxml.etree.c:95786)
  File "parser.pxi", line 618, in lxml.etree._raiseParseError (src\lxml\lxml.etree.c:94818)
IOError: Error reading file 'report_email.html': failed to load external entity "report_email.html"

Upvotes: 0

Views: 1620

Answers (2)

PascalVKooten
PascalVKooten

Reputation: 21461

Just try yagmail. As written in the readme, that is one of its main purposes.

What is funny is that you can even use it on the command line.

yagmail -t [email protected] -s "this is the subject" -c test.html

-t and -s are self explanatory, -c just stands for "content".

Or just in python.

import yagmail
yagmail.SMTP().send("[email protected]", "this is the subject", "test.html")

The way it works is that if you send something that can be loaded as file it will be attached. In case of images and html, they will be put inline.

Also notice that you don't have any login information. If you set it up once (save password in keyring, and have your username in a .yagmail in your home folder), you will never have to put your login/password in scripts.

Upvotes: 1

Mochamethod
Mochamethod

Reputation: 276

This function should allow you to define to and from addresses, as well as the contents of messages through html. My html is kind of sketchy, being that I mostly work in Java and Python. Hopefully this does the trick for you.

#REQUIRED IMPORTS
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def Send_Email():
    inpadd = "[email protected]"     #Input and output email addresse.
    outadd = "[email protected]"   #They define the 'To' and 'From'

    if (inpadd and outadd) != '':
        msg = MIMEMultipart('alternative')      #Defining message variables
        msg['Subject'] = "TEXT"
        msg['From'] = inpadd
        msg['To'] = outadd

        text = "TEXT\nTEXT\nTEXT\nhttp://www.wikipedia.org"  #HTML information
        html = """\     
        <html>
            <head></head>
              <body>
                <p>TEXT<br>
                TEXT<br>
                TEXT <a href="http://www.wikipedia.org">LINKNAME</a>. 
              </p>
            </body>
        </html>
        """
        part1 = MIMEText(text, 'plain')
        part2 = MIMEText(html, 'html')

        msg.attach(part1)
        msg.attach(part2)

        s = smtplib.SMTP('localhost')
        s.sendmail(inpadd, outad, msg.as_string())  #Requires three variables, in address, out address, and message contents.
        s.quit()            
    else:
        print "Either the input or output address has not been defined!"

if __name__ == '__main__':
    Send_Email()

Upvotes: 0

Related Questions