如何在python中将html文件作为电子邮件发送?

时间:2016-01-26 13:54:19

标签: python html python-2.7 email

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 <sam14@gmail.com>
    To: sam <sam14@gmail.com>
    MIME-Version: 1.0
    Content-type: text/html
    Subject: %s

    %s""" %(page, content)


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

在上面的代码中:首先,我在目录中找到* .html文件。我发现它,它对我来说很好。后来我想把这个html文件作为电子邮件发送给某个人。我失败了。有人可以建议我怎么做吗? 打印文件名:正在打印目录中的html文件列表,我在将文件作为电子邮件发送时遇到问题。 我收到的错误是:

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"

2 个答案:

答案 0 :(得分:1)

试试yagmail。正如自述文件中所述,这是其主要目的之一。

有趣的是,您甚至可以在命令行中使用它。

yagmail -t toaddress@gmail.com -s "this is the subject" -c test.html

-t-s是不言自明的,-c仅代表“内容”。

或者只是在python中。

import yagmail
yagmail.SMTP().send("toaddress@gmail.com", "this is the subject", "test.html")

它的工作方式是,如果您发送可以作为文件加载的内容,它将被附加。如果是图像和html,它们将被内联。

另请注意,您没有任何登录信息。如果您将其设置一次(save password in keyring,并将您的用户名放在主文件夹中的.yagmail),则无需将您的登录名/密码放在脚本中。

答案 1 :(得分:0)

此功能应允许您通过html定义往返地址以及消息内容。我的html有点粗略,因为我主要使用Java和Python。希望这对你有用。

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

def Send_Email():
    inpadd = "my@email.com"     #Input and output email addresse.
    outadd = "your@email.com"   #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()