《运维--PlayBook》更新中.......!请访问: https://ops.cnmysql.com

Python发送邮件 (STMPLib) 不指定

kangyang , 2014/08/13 18:16 , Python , 评论(0) , 阅读(3809) , Via 本站原创
python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。

smtp协议的基本命令包括:
HELO 向服务器标识用户身份
MAIL 初始化邮件传输 mail from:
RCPT 标识单个的邮件接收人;常在MAIL命令后面,可有多个rcpt to:
DATA 在单个或多个RCPT命令后,表示所有的邮件接收人已标识,并初始化数据传输,以.结束
VRFY 用于验证指定的用户/邮箱是否存在;由于安全方面的原因,服务器常禁止此命令
EXPN 验证给定的邮箱列表是否存在,扩充邮箱列表,也常被禁用
HELP 查询服务器支持什么命令
NOOP 无操作,服务器应响应OK
QUIT 结束会话
RSET 重置会话,当前传输被取消
MAIL FROM 指定发送者地址
RCPT TO 指明的接收者地址

Python创建 SMTP 对象:
import smtplib
SMTPObj = smtplib.SMTP( [host [,port [,local_hostname]]] )

参数说明:

    host: SMTP 服务器主机。 你可以指定主机的ip地址或者域名如:i-it.info,这个是可选参数。
    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协议中定义的格式。


一个发送邮件的小例子:
import smtplib

send = '18717776124@163.com'
receivers = ['itchenyi@gmail.com']
UserPass = ['18717776124@163.com','%password%']

message = """From: From Person <18717776124@163.com>
TO: To Person <itchenyi@gmail.com>
Subject: SMTP e-mail test

This is a test email message.
"""

try:
    SMTPObj = smtplib.SMTP("smtp.163.com","25")
    SMTPObj.login('%s'%UserPass[0],"%s"%UserPass[1])
    SMTPObj.sendmail(send,receivers,message)
    SMTPObj.quit()
    print "Successfully sent email"
except:
    print "Error: unable to send email"


用python发送HTML格式的邮件:
###Python发送HTML格式的邮件与发送纯文本消息的邮件不同之处就是将MIMEText中_subtype设置为html###
import smtplib
from email.mime.text import MIMEText

mailto_list = ["itchenyi@gmail.com"]
mail_host = "smtp.163.com"
##smtp server##
mail_user = "18717776124"
##username##
mail_pass = "%password%"
##password##
mail_postfix = "163.com"
##后缀##

def send_email(to_list,sub,content):
###定义收件人列表,主题,邮件内容###
me = "hello"+"<"+mail_user+"@"+mail_postfix+">"
###hello信息###
msg = MIMEText(content,_subtype='html',_charset='utf8')
###创建实例,设置为html格式##
msg['Subject'] = sub
###主题###
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
s = smtplib.SMTP()
s.connect(mail_host)
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_email(mailto_list,"hello","<a href="http://www.ipython.me">IT辰逸</a>"):
print "send Successfully"
else:
print "send Error"



Python 发送带附件的邮件:
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib

##创建一个带附件的实例##
msg = MIMEMultipart()

##构造附件##
att_one = MIMEText(open('D:\\testfile','rb').read(),'base64','utf8')
att_one["Content-Type"] = 'application/octet-stream'
att_one["Content-Disposition"] = 'attachment; filename="testfile"'
msg.attach(att_one)

##构造附件##
att_two = MIMEText(open('D:\\testfile.zip','rb').read(),'base64','utf8')
att_two["Content-Type"] = 'applecation/octet-stream'
att_two["Content-Disposition"] = 'attachment; filename="testfile.zip"'
msg.attach(att_two)

##邮件头##
msg['to'] = "itchenyi@gmail.com"
msg['from'] = '18717776124@163.com'
msg['subject'] = 'test email'

##发送邮件##
try:
    server = smtplib.SMTP()
    server.connect('smtp.163.com')
    server.login('18717776124@163.com','%password%')
    server.sendmail(msg['from'],msg['to'],msg.as_string())
    server.quit()
    print "send Successfully"
except Exception,e:
    print str(e)


Python 发送带图片的HTML邮件:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

send = '18717776124@163.com'
receiver = 'itchenyi@gmail.com'
subject = 'email test'
username = '18717776124@163.com'
password = '%password%'

msg = MIMEMultipart('related')
msg['subject'] = 'test email'

msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>good!','html','utf-8')
msg.attach(msgText)

fp = open('D:\\i-it.jpg','rb')
msgImage = MIMEImage(fp.read())
fp.close()

msgImage.add_header('Content-ID', '<image1>')
msg.attach(msgImage)

try:
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(send, receiver, msg.as_string())
smtp.quit()
print "send Successfully"
except Exception,e:
print str(e)


Python 发送包含多种元素的邮件
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

send = '18717776124@163.com'
receiver = 'itchenyi@gmail.com'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '18717776124@163.com'
password = '%password%'

msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"

text = "Hi!\nHow are you?"
html = """
Hi!
How are you?
"""

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(part1)
msg.attach(part2)

att = MIMEText(open('d:\\i-it.jpg', 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="iit.jpg"'
msg.attach(att)

try:
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(send, receiver, msg.as_string())
smtp.quit()
print "send Successfully"
except Exception,e:
print str(e)
Tags: , ,
分页: 1/1 第一页 1 最后页 [ 显示模式: 摘要 | 列表 ]