使用python多线程的Html电子邮件

时间:2016-03-02 07:42:55

标签: python python-multithreading

我正在尝试使用python代码将html邮件发送给多个收件人,但代码将html邮件作为附件发送,但我不想将其作为附件发送这是我编写的代码段。

#!/usr/bin/python
import xlrd
import threading
import time
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from string import Template

exitFlag = 0

location= "Book1.xlsx"
workbook = xlrd.open_workbook(location)
sheet = workbook.sheet_by_index(0)
offset = 0

rows = []
email=[]
name=[]
for i, col in enumerate(range(sheet.ncols)):
  if i in range(1,3):
        continue
  r = []
  for j, row in enumerate(range(sheet.nrows)):
    r.append(sheet.cell_value(j, i))
 rows.append(r)

email= rows[1]
name= rows[0]

class SendMail(threading.Thread):
  def __init__(self, fro, to, subject, new):
    threading.Thread.__init__(self)
    self.fro = fro
    self.to = to
    self.subject = subject
    self.new = new 
  def run(self):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = self.subject
    msg['From'] = self.fro
    msg['To'] = self.to
    msg.attach(MIMEText(self.new , 'new'))
    print "WELCOME"

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(self.fro, "****")                
    server.sendmail(self.fro, self.to, msg.as_string())
    server.quit()

def final():
  fro = "a@gmail.com"
  subject = "hello"
  html= """\
<html>
  <head></head>
  <body>
    <p>Thank you for being a loyal customer.<br>
       Here is your unique code to unlock exclusive content:<br>
       <br><br><h1>$code</h1><br>
    </p>
  </body>
</html>
"""

  for s in range(len(email)):
    line= email[s]
    print email[s]
    new = Template(html).safe_substitute(code= name[s])
    t = SendMail(fro, line, subject, new)
    t.start()

for i in range(1):
  final()

1 个答案:

答案 0 :(得分:1)

您需要在调用时为邮件设置正确的MIME子类型。

msg.attach(MIMEText(self.new , 'new')) # no valid subtype

第二个参数不是标签,而是文本的子类型。

您希望将HTML用作子类型。

msg.attach(MIMEText(self.new , 'html'))