如何在python脚本中将csv文件中的内容插入电子邮件的html内容中

时间:2017-04-19 16:11:22

标签: python python-2.7

我有csv文件,它有不同字段的电子邮件列表。现在,我需要向CSV文件中的所有电子邮件发送html内容电子邮件。我编写了代码,但我无法从csv文件中动态插入值。

这是我的代码。

import csv
import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

with open('accountlockout.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        #print(row['first_name'], row['last_name'])
        FROM = 'noreply@domain.com' 
        TO = row['email']
        print (TO)
        #RECIPIENT = [TO] + [CC]
        msg = MIMEMultipart('alternative')
        msg['Subject'] = "Notification"
        msg['From'] = FROM
        msg['To'] = TO
        #msg['Cc'] = CC
        first = row['first']
        print (first)
        ltime = row['ltime']
        user = row['user']
        host = row['host']
        dest_nt_host = row['dest_nt_host']
        html="""
        <html>
                <head>
                <style>
                        p.serif {
                        font-family: "EK03Plain-L01", Times, serif;
                        }
                </style>
                </head>
                <body>
                <p class="serif">Dear first 
                <table border="1">
                        <tr>
                                <th>Date/Time</th>
                                <th>Username</th>
                                <th>Workstation/Server</th>
                                <th>Presumed Location</th>
                        </tr>
                        <tr>
                                <td>ltime</td>
                                <td>user</td>
                                <td>host</td>
                                <td>dest_nt_host</td>
                        </tr>
                </table>

        </body>
        </html>
        """

        # Prepare actual message
        part1 = MIMEText(html, 'html')

        msg.attach(part1)

        # Send the mail
        server = smtplib.SMTP("smtp.gmail.com")
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login("something","something")
        server.sendmail(FROM, TO, msg.as_string())
        print ("sucess")
server.quit()

我需要在电子邮件正文中的表格中插入来自csv文件的值。 请帮帮我..

0 个答案:

没有答案