我是新的蟒蛇.. 其實,我試圖發送精選的電子郵件與Python:HTML身體,文本替代身體和附件。Python的phpMailer php類在哪裏等同?
所以,我發現這個tutorial,使用Gmail認證適應它(教程中here)
代碼中,我有個大氣壓,就是:
def createhtmlmail (html, text, subject):
"""Create a mime-message that will render HTML in popular
MUAs, text in better ones"""
import MimeWriter
import mimetools
import cStringIO
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
out = cStringIO.StringIO() # output buffer for our message
htmlin = cStringIO.StringIO(html)
txtin = cStringIO.StringIO(text)
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()
#
# the plain text section
#
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
mimetools.encode(txtin, pout, 'quoted-printable')
txtin.close()
#
# 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", 'us-ascii')])
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
import smtplib
f = open("/path/to/html/version.html", 'r')
html = f.read()
f.close()
f = open("/path/to/txt/version.txt", 'r')
text = f.read()
subject = "Prova email html da python, con allegato!"
message = createhtmlmail(html, text, subject)
gmail_user = "[email protected]"
gmail_pwd = "thegmailpassword"
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(gmail_user, gmail_pwd)
server.sendmail(gmail_user, "[email protected]", message)
server.close()
和工作..現在只錯過附件.. 而我無法添加附件(從this後)
那麼,爲什麼沒有像phpMailer的PHP類的Python類? 這是因爲,對於一箇中等能力的Python程序員發送帶附件和ALT文本正文的HTML電子郵件是如此容易以至於不需要一個類? 還是因爲我只是沒有找到它?
如果我能寫一個這樣的類,當我用python寫得夠好的時候,會對某人有用嗎?
在示例中添加替代文字,你有一個勝利者! – YHVH 2009-04-30 18:32:18