我正在尝试编写一个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 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()