0

I am trying to write a python code to send html mail with an attachment to multiple recipients using multi-thread.I could only send the html part but i could not figure out how to send attachment and the text message. Here is the 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 email.MIMEBase import MIMEBase
from email import encoders
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, files ):
    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 , 'html'))

    part = MIMEBase('application', 'octet-stream')
    encoders.encode_base64(part)
    msg.attach(part)
    print "WELCOME"

    smtp_server = '*****'
    smtp_username = '*****'
    smtp_password = '*****'
    smtp_port = '587'
    smtp_do_tls = True

    server = smtplib.SMTP(
        host = smtp_server,
        port = smtp_port,
        timeout = 10
    )
    server.starttls()
    server.login(smtp_username, smtp_password)                
    server.sendmail(self.fro, self.to, msg.as_string())
    server.quit()

def final():
  fro = "t@domain.com"
  subject = "hello"
  text= "hello people"
  html= """\
<html>
  <head></head>
  <body>
    <p>Thank you $code 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>
"""

  filename = "knowledge.jpg"
  files = open("C:\Python27\PROJECTS\knowledge.jpg", "rb")

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

for i in range(1):
  final()
Akanksha Singla
  • 143
  • 1
  • 11

0 Answers0