python 发送Email程序

来源:互联网 发布:linux删除mysql数据库 编辑:程序博客网 时间:2024/05/19 19:30

python 发送邮件需要用到 smtplib和 email 这两个库

smtplib 用于发送邮,smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装 使用方法如下:

#连接到SMTP服务器

SMTP.connect(host, port) #host服务器地址 port 用到端口

#登录到SMTP服务器

SMTP.login(user, password)

#发送邮件

SMTP.sendmail(from_addrs, to_addrs, msg)

#断开连接

SMP.quit()

参数说明:

from_addr: 邮件发送者地址

to_addrs: 字符串列表,邮件发送地址

msg: 发送消息, msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。这个格式就是smtp协议中定义的格式。

email库用来处理邮件消息,也就是构造上面的msg

一、发送简单邮件,不包含附件的文本邮件

程序如下:

from email.MIMEText import MIMEText#邮件正文mail_body = "this is a simple email"#发件人mail_from='sender@example.com'# 收件人mail_to=['to@example.com'] #可以是多个msg=MIMEText(mail_body,'plain','utf−8')#邮件头msg['Subject']='this is the title'msg['From']=mail_frommsg['To']=';'.join(mail_to)#邮件发送时间(不定义的可能有的邮件客户端会不显示发送时间)msg['date']=time.strftime('%a, %d %b %Y %H:%M:%S %z')smtp=smtplib.SMTP()#连接SMTP服务器,此处用的126的SMTP服务器smtp.connect('smtp.126.com')#用户名密码smtp.login('用户名','密码')smtp.sendmail(mail_from,mail_to,msg.as_string())smtp.quit()

二 、 发送带附件的邮件

发送带附件的邮件,首先要创建MIMEMultipart实例,然后构造附件,如果有多个附件,可依次构造。

程序如下:

import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.image import MIMEImage#创建实例,构造MIMEMultipart对象做为根容器msg=MIMEMultipart()msg['Subject']='this is title'msg['From']=mail_frommsg['To']=';'.join(mail_to)# 构造MIMEText对象做为邮件显示内容并附加到根容器txt=MIMEText(u'这是中文内容哦','plain','utf-8')msg.attach(txt)picfiles=['', '', ...] #图片路径for file in picfiles:f=open(file,'rb')img=MIMEImage(f.read())f.close()msg.attach(img)#文本附件att = MIMEText(open(r'/home/test/123.txt', 'rb').read(), 'base64', 'gb2312')att["Content-Type"] = 'application/octet-stream'att["Content-Disposition"] = 'attachment; filename="123.txt'#这里的filename可以任意写,写什么名字,邮件中显示什么名字msg.attach(att)smtp=smtplib.SMTP()smtp.connect('smtp.126.com')smtp.login('用户名','密码')smtp.sendmail(mail_from,mail_to,msg.as_string())smtp.quit()

三、发送HTML邮件

 multipart使用alternative类型,这样就可以让客户端来决定显示HTML类型还是text类型。

 程序如下:


import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText#建立消息容器,正确的MIME类型是multipart/alternativemsg=MIMEMultipart('alternative')msg['subject']='link'msg['from']=mail_frommsg['to']=';'.join(mail_to)text="Hello!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"html="""\Hello!How are you?Here is the link you wanted."""part1=MIMEText(text,'plain')part2=MIMEText(html,'html')msg.attach(part1)msg.attach(part2)

相关文档地址:http://docs.python.org/library/email-examples.html

0 0
原创粉丝点击