使用python和html发送邮件

时间:2019-06-21 06:44:42

标签: python html mysql email

我正在尝试从SQL查询中获取结果集,并将其添加到我的电子邮件模板(HTML文件)中。

两个功能:

一个用于邮件摘要,另一个用于更改电子邮件正文。

我正在使用python的smtplib和电子邮件软件包发送邮件。

#send a email

from fileOps import fileOps
from dbOps import dbOps
import smtplib
from smtplib import SMTP, SMTPException
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

mailFrom = ''
password = ''
mailTo = ''
mailServer = 'smtp.gmail.com'
port = 587
s = smtplib.SMTP(mailServer,port)

#function for email summary 
def emailSummary():
    try:
        #security
        s.starttls()
        s.login(mailFrom,password)

        #for fetching all the records
        dbObj = dbOps()
        db = dbObj.connectDB()
        sql = "SELECT DISTINCT CASE_MASTER.AGREEMENTID, CASE_MASTER.NO_OF_FILES FROM " \
              "CASE_MASTER LEFT JOIN CASE_FILE_STATUS ON CASE_FILE_STATUS.MOVED_TO_AWS_FLAG = CASE_MASTER.MOVED_TO_AWS_FLAG " \
              "AND CASE_FILE_STATUS.MOVED_TO_AWS_Date AND CASE_MASTER.MOVED_TO_AWS_FLAG IS NOT NULL " \
              "WHERE CASE_FILE_STATUS.MOVED_TO_AWS_FLAG = 1 AND CASE_FILE_STATUS.MOVED_TO_AWS_Date IS NOT NULL"
        resultSet = dbObj.readData(db, sql)

        getEmailBody(resultSet)

        emailBody = getEmailBody(resultSet)
        s.sendmail(mailFrom, mailTo,emailBody)
        s.quit()
 #       print("Email Successfully sent !!! ")
    except smtplib.SMTPException as e :
        print(e)

#function to get emailBody 
def getEmailBody(resultSet):
    try:
        htmlTemplate = open('summaryTemplate.html', 'r')
        alert_msg = MIMEText(htmlTemplate.read(), "html", "utf-8")
        html = htmlTemplate.read()
        part1 = MIMEText(html, 'html')
        part2 = """<table>
                    % for r in resultSet:
                        <tr>
                            % for cell in r:
                                <td>${cell}</td>
                        % endfor</tr>
                    % endfor</table>""".format(**locals())

        msg = MIMEMultipart('alternative')
        msg['Subject'] = "HERO_FC_DM_DB"
        msg['From'] = mailFrom
        msg['To'] = mailTo
        msg.attach(part1)


    except Exception as e:
        print(e)

emailSummary()

我正在获取该行,但未从该行获取内容

['81173'] 'cell'

 File "C:\Users\sailee.pawar\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py", line 858, in sendmail
    esmtp_opts.append("size=%d" % len(msg))
'cell'
TypeError: object of type 'NoneType' has no len()

我收到上述错误 追溯(最近一次通话): 第68行,在emailSummary()中 电子邮件摘要中的第37行 s.sendmail(mailFrom,mailTo,emailBody) 第858行,在sendmail中esmtp_opts.append(“ size =%d”%len(msg)) '细胞' TypeError:“ NoneType”类型的对象没有len()

expected  o/p :
['81173']
'file1.jpg'
'file2.txt'

0 个答案:

没有答案