私はpythonを初めて使用します..実際、私はpythonを使用して注目のメールを送信しようとしています:html本文、テキスト代替本文、および添付ファイル。
だから、私はこのチュートリアルを見つけて、それをgmail認証に適応させました(チュートリアルはここにあります)
私が持っているコードは次のとおりです。
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 = "thegmailaccount@gmail.com"
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, "example@example.com", message)
server.close()
そして、それは機能します..今は添付ファイルを見逃すだけです..そして、添付ファイルを追加できません(この投稿から)
では、なぜ phpMailer for php のような python クラスがないのでしょうか? 中程度の Python プログラマーにとって、添付ファイルと代替テキスト本文を含む HTML メールを送信するのは非常に簡単で、クラスは必要ないからですか? それとも私が見つけられなかったからですか?
私がそのようなクラスを書くことができれば、私がPythonに十分慣れたときに、それは誰かにとって役に立ちますか?