Форум сайта python.su
Всем доброго!
Честно говоря не пойму, где нужно поставить кодировку чтобы письма приходили в нормальном виде (кодировка: cp1251), вследующем скрипте
import urllib
import smtplib
def createhtmlmail (html, subject):
"""Create a mime-message that will render HTML in popular
MUAs, text in better ones"""
import MimeWriter
import mimetools
import cStringIO
out = cStringIO.StringIO() # output buffer for our message
htmlin = cStringIO.StringIO(html)
writer = MimeWriter.MimeWriter(out)
#
# set up some basic headers... we put subject here
# because smtplib.sendmail expects it to be in the
# message body
#
writer.addheader("Subject", subject)
writer.addheader("MIME-Version", "1.0")
#
# start the multipart section of the message
# multipart/alternative seems to work better
# on some MUAs than multipart/mixed
#
writer.startmultipartbody("alternative")
writer.flushheaders()
#
# start the html subpart of the message
#
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
#
# returns us a file-ish object we can write to
#
pout = subpart.startbody("text/html", [("charset", 'cp-1251')])
mimetools.encode(htmlin, pout, 'quoted-printable')
htmlin.close()
#
# Now that we're done, close our writer and
# return the message body
#
writer.lastpart()
msg = out.getvalue()
out.close()
return msg
# Формирование файла weather.html
citycode = '27612'
_url = "http://www.gismeteo.ru/towns/" + citycode + ".htm"
skin = 'default'
u = urllib.urlopen(_url)
s = u.read()
p1 = s.find('var frc=\'') + 9
p2 = s.find('\'',p1)
s = s[p1:p2]
s = s.replace('align=center ', '')
s = s.replace('<span class=sml>', '')
s = s.replace('</span>', '')
s = s.replace('nowrap', 'nowrap="true"')
s = s.replace('<table', '<table class="tbl"')
s = s.replace('bgcolor=F0F0F0', 'class="cl1"')
s = s.replace('bgcolor=F0FFF0', 'class="cl2"')
s = s.replace('bgcolor=F0F0FF', 'class="cl3"')
s = s.replace('bgcolor=FFF0F0', 'class="cl4"')
s = s.replace('bgcolor=FFFFF0', 'class="cl5"')
s = s.replace('bgcolor=FFFFFF', 'class="cl6"')
b = 1
while b:
p1 = s.find('<img')
if p1 == -1:
b = 0
else:
p2 = s.find('>',p1)
if p2 == -1:
b = 0
else:
_oldstr = s[p1:p2+1]
_newstr = ''
pp1 = _oldstr.find('title="')
if pp1 > -1:
pp2 = _oldstr.find('"',pp1+7)
if pp2 > -1:
_newstr = _oldstr[pp1+7:pp2]
s = s.replace(_oldstr, _newstr)
f = open('weather.html', 'w')
f.write('<html>\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">\n</head>\n<body>\n')
f.write(s+'\n')
f.write('</body>\n</html>')
f.close()
#Отправка почты
html = open("weather.html").read()
subject = "Погода сегодня!"
message = createhtmlmail(html, subject)
server = smtplib.SMTP("111.111.111.111")
server.sendmail('my@mail.ru', ['you@mail.ru'], message)
server.quit()
Отредактировано (Фев. 4, 2009 08:03:24)
Офлайн