Python 發送Mail范例包括:簡單的、HTML的、附檔的
#smtp test
import smtplib
#smtpServer = 'exdg.yydg.com.cn'
smtpServer = 'dgm2k.yydg.com.cn'
fromaddr = 'lk@yy3.yydg.com.cn'
toaddrs = 'lk@yy3.yydg.com.cn'
msg = 'Subject: Test'
server = smtplib.SMTP(smtpServer)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
#sendmail with mimebase
# coding=utf-8
import smtplib
import os,sys,codecs,string
import locale
from optparse import OptionParser
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
me = "lk@yy3.yydg.com.cn"
you = "lk@yy3.yydg.com.cn"
server = "dgm2k.yydg.com.cn"
#server = "exdg.yydg.com.cn"
#text = "Hi!/nHow are you?/nHere is the link you wanted:/nhttp://www.python.org"
html = """/
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?您好,劉科<br>
Here is the http://www.python.org you wanted.
</p>
</body>
</html>
"""
f = 'PythonEx.zip'
msg = MIMEMultipart()
msg['From'] = me
msg['To'] = you
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = 'test attach file測試附檔文件'
#msg.attach(MIMEText(text))
part2 = MIMEText(html, 'html', 'utf-8')
msg.attach(part2)
part = MIMEBase('application', "octet-stream")
s=open(f,"rb").read()
part.set_payload( s )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
msg.attach(part)
smtp = smtplib.SMTP(server)
smtp.sendmail(me, you, msg.as_string())
smtp.close()
print "OK"
print msg.as_string()
本文提供了使用Python通过SMTP服务器发送邮件的示例代码,包括简单的纯文本邮件、带有HTML格式的邮件以及包含附件的邮件。示例展示了如何利用smtplib模块及email.mime系列模块来构造复杂的邮件内容。
663

被折叠的 条评论
为什么被折叠?



