使用smtplib发送邮件

来源:互联网 发布:云笔记本 知乎 编辑:程序博客网 时间:2024/05/21 14:43

smtplib,email 发送邮件的一般流程
先构造邮件的message部分
使用email的mine

最常见的MIME首部是以Content-Type开头的:
1) Content-Type: multipart/mixed 它表明这封Email邮件中包含各种格式的MIME实体但没有具体给出每个实体的类型。
2) Content-Type: multipart/alternative 如果同一封Email邮件既以文本格式又以HTML格式发送,那么要使用Content-Type: multipart/alternative。这两种邮件格式实际上是显示同样的内容但是具有不同的编码。
3) Content-Type: multipart/related 用于在同一封邮件中发送HTML文本和图像或者是其他类似类型。
邮件主体的编码:主要是包括quoted-printable与base64两种类型的编码。Base64和Quoted-Printable都属于MIME(多用途部分、多媒体电子邮件和 WWW 超文本)的一种编码标准,用于传送诸如图形、声音和传真等非文本数据)。
以上内容转自http://www.tuicool.com/articles/byINN3

1.mimemultipart对象 为邮件的容器

import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.application import MIMEApplicationfrom email.header import Headermsg = MIMEMultipart("alternative")msg["Subject"] = "test subject"msg["From"] = frommsg["To"] = to

2.把邮件的内容attach到msg上

text_part = MIMEText("text part")msg.attach(text_part)//attach一个text#======================================html_file = open("D:/d.html","rb")html_text = MIMEText(html_file.read(),'html','utf-8')html_file.close()msg.attach(html_text)//attach一个html#======================================png_file = open("D:/256.png",'rb')png_part = MIMEImage(png_file.read())png_part.add_header('Content-ID','<image1>')msg.attach(png_part)//attach一个png到html内容中png_file.close()#======================================file_attachment.add_header('Content-Disposition', 'attachment', filename = "filename")//attach为附件的写法#======================================#如果使用MIMEApplication,则text1 = MIMEApplication(text,"html")text1.add_header("Content-Type","text/html")msg.attach(text1)

3.使用smtplib登录smtp服务器

s = smtplib.SMTP_SSL("smtp.qq.com","465")s.login(user,pwd)s.sendmail(user,to,msg.as_string())s.close()

有很多地方还是不懂,仍需要学习

官方文档
email:https://docs.python.org/2/library/email-examples.html
smtplib:https://docs.python.org/2/library/smtplib.html

关于MIME的文章
http://blog.csdn.net/xiemk2005/article/details/6111614

0 0