Python 發送Mail

本文提供了使用Python通过SMTP服务器发送邮件的示例代码,包括简单的纯文本邮件、带有HTML格式的邮件以及包含附件的邮件。示例展示了如何利用smtplib模块及email.mime系列模块来构造复杂的邮件内容。

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()

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值