smtp(simple mail transfer protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。
python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。
python创建 smtp 对象语法如下:
import smtplib
smtpobj = smtplib.smtp( [host [, port [, local_hostname]]] )
参数说明:
host: smtp 服务器主机。 你可以指定主机的ip地址或者域名如:ziqiangxuetang.com,这个是可选参数。
port: 如果你提供了 host 参数, 你需要指定 smtp 服务使用的端口号,一般情况下smtp端口号为25。
local_hostname: 如果smtp在你的本机上,你只需要指定服务器地址为 localhost 即可。
python smtp对象使用sendmail方法发送邮件,语法如下:
smtp.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]
参数说明:
from_addr: 邮件发送者地址。
to_addrs: 字符串列表,邮件发送地址。
msg: 发送消息
这里要注意一下第三个参数,msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。这个格式就是smtp协议中定义的格式。
实例
以下是一个使用python发送邮件简单的实例:
#!/usr/bin/python
import smtplib
sender = ‘from@fromdomain.com’
receivers = [‘to@todomain.com’]
message = “””from: from person
to: to person
subject: smtp e-mail test
this is a test e-mail message.
“””
try:
smtpobj = smtplib.smtp(‘localhost’)
smtpobj.sendmail(sender, receivers, message)
print “successfully sent email”
except smtpexception:
print “error: unable to send email”
使用python发送html格式的邮件
python发送html格式的邮件与发送纯文本消息的邮件不同之处就是将mimetext中_subtype设置为html。具体代码如下:
import smtplib
from email.mime.text import mimetext
mailto_list=[“yyy@yyy.com”]
mail_host=”smtp.xxx.com” #设置服务器
mail_user=”xxx” #用户名
mail_pass=”xxxx” #口令
mail_postfix=”xxx.com” #发件箱的后缀
def send_mail(to_list,sub,content): #to_list:收件人;sub:主题;content:邮件内容
me=”hello”+”” #这里的hello可以任意设置,收到信后,将按照设置显示
msg = mimetext(content,_subtype=’html’,_charset=’gb2312′) #创建一个实例,这里设置为html格式邮件
msg[‘subject’] = sub #设置主题
msg[‘from’] = me
msg[‘to’] = “;”.join(to_list)
try:
s = smtplib.smtp()
s.connect(mail_host) #连接smtp服务器
s.login(mail_user,mail_pass) #登陆服务器
s.sendmail(me, to_list, msg.as_string()) #发送邮件
s.close()
return true
except exception, e:
print str(e)
return false
if __name__ == ‘__main__’:
if send_mail(mailto_list,”hello”,”小五义”):
print “发送成功”
else:
print “发送失败”
或者你也可以在消息体中指定content-type为text/html,如下实例:
#!/usr/bin/python
import smtplib
message = “””from: from person
to: to person
mime-version: 1.0
content-type: text/html
subject: smtp html e-mail test
this is an e-mail message to be sent in html format
this is html message.
this is headline.
“””
try:
smtpobj = smtplib.smtp(‘localhost’)
smtpobj.sendmail(sender, receivers, message)
print “successfully sent email”
except smtpexception:
print “error: unable to send email”
python发送带附件的邮件
发送带附件的邮件,首先要创建mimemultipart()实例,然后构造附件,如果有多个附件,可依次构造,最后利用smtplib.smtp发送。
from email.mime.text import mimetext
from email.mime.multipart import mimemultipart
import smtplib
#创建一个带附件的实例
msg = mimemultipart()
#构造附件1
att1 = mimetext(open(‘d:\\123.rar’, ‘rb’).read(), ‘base64’, ‘gb2312’)
att1[“content-type”] = ‘application/octet-stream’
att1[“content-disposition”] = ‘attachment; filename=”123.doc”‘#这里的filename可以任意写,写什么名字,邮件中显示什么名字
msg.attach(att1)
#构造附件2
att2 = mimetext(open(‘d:\\123.txt’, ‘rb’).read(), ‘base64’, ‘gb2312’)
att2[“content-type”] = ‘application/octet-stream’
att2[“content-disposition”] = ‘attachment; filename=”123.txt”‘
msg.attach(att2)
#加邮件头
msg[‘to’] = ‘yyy@yyy.com’
msg[‘from’] = ‘xxx@xxx.com’
msg[‘subject’] = ‘hello world’
#发送邮件
try:
server = smtplib.smtp()
server.connect(‘smtp.xxx.com’)
server.login(‘xxx’,’xxxxx’)#xxx为用户名,xxxxx为密码
server.sendmail(msg[‘from’], msg[‘to’],msg.as_string())
server.quit()
print ‘发送成功’
except exception, e:
print str(e)
以下实例指定了content-type header 为 multipart/mixed,并发送/tmp/test.txt 文本文件:
#!/usr/bin/python
import smtplib
import base64
filename = “/tmp/test.txt”
# 读取文件内容并使用 base64 编码
fo = open(filename, “rb”)
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
sender = ‘webmaster@tutorialpoint.com’
reciever = ‘amrood.admin@gmail.com’
marker = “auniquemarker”
body =”””
this is a test email to send an attachement.
“””
# 定义头部信息
part1 = “””from: from person
to: to person
subject: sending attachement
mime-version: 1.0
content-type: multipart/mixed; boundary=%s
–%s
“”” % (marker, marker)
# 定义消息动作
part2 = “””content-type: text/plain
content-transfer-encoding:8bit
%s
–%s
“”” % (body,marker)
# 定义附近部分
part3 = “””content-type: multipart/mixed; name=\”%s\”
content-transfer-encoding:base64
content-disposition: attachment; filename=%s
%s
–%s–
“”” %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpobj = smtplib.smtp(‘localhost’)
smtpobj.sendmail(sender, reciever, message)
print “successfully sent email”
except exception:
print “error: unable to send email”