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

2024-10-01 22:25:34 发布

您现在位置: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 <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文件列表,我无法通过电子邮件发送文件。 我得到的错误是:

^{pr2}$

Tags: 文件importcomoshtmlpagerootfilename
2条回答

此函数应允许您定义“收件人”和“发件人”地址,以及通过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()

{试一下}。正如自述中所写,这是它的主要目的之一。在

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

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

-t和{}是不言而喻的,-c只是“内容”的意思。在

或者只是在python中。在

^{pr2}$

它的工作方式是,如果你发送的东西可以作为文件加载,它将被附加。如果是图像和html,它们将被放入内联。在

还请注意,您没有任何登录信息。如果您设置一次(save password in keyring,并且您的用户名位于主文件夹中的.yagmail),您就不必在脚本中输入登录名/密码。在

相关问题 更多 >

    热门问题