Akanksha Singla
Akanksha Singla

Reputation: 143

Html emails using python multithread

I am trying a python code to send html mail to multiple recipients, but the code sends the html mail as an attachment, but i dont want to send it as attachment Here is the piece of code i have written.

#!/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 = "[email protected]"
  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()

Upvotes: 1

Views: 840

Answers (1)

DreyFax
DreyFax

Reputation: 427

You need to set the correct MIME-Subtype for your message when calling.

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

The second parameter is not a label, but the subtype of the text.

You want to use HTML as subtype.

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

Upvotes: 1

Related Questions