SMTP是发送邮件的协议,python内置对SMTP的支持,可以发送纯文本邮件,html以及带附件的邮件。
python对SMTP的支持有smtplib和email两个模块,email模块负责构造邮件,smtplib模块负责发送邮件。
smptlib模块主要负责发送邮件,是一个发送邮件的动作:连接邮箱服务器,登录邮箱,发送邮件(有发件人,收件人,发件内容等)
email模块主要负责构建邮件:指的是邮箱页面显示的一些构造:如发件人,收件人,主题,正文,附件等。
1、smtplib模块:
smtplib的使用比较简单
import smtplib
server = smtplib.SMTP(smtp_server, port) # smtp_server:指定连接的邮箱smtp服务器地址 port:指定连接服务器端口
server.login(from_addr, password) # from_addr:登录邮箱的用户名;password:登录用的密码,这里的密码不是邮箱本身的密码,而是邮箱设置中的授权码
server.sendmail(from_addr, [to_addr], msg.to_string()) # from_addr:发件人,to_addr:收件人,这里收件人是一个列表,可以有多个;msg:发送内容,内容是一个str
server.quit() #结束smtp会话。
1)我们可以设置debug打印出和SMTP服务器交互的所有信息:server.set_debuglevel(1)
2)常用的smtp服务器有:
smtp.qq.com(QQ邮箱);smtp.sina.com(新浪);smtp.126.com(126邮箱);smtp.139.com(139邮箱);smtp.163.com(163邮箱);smtp.sohu.com(搜狐邮箱)等
2、email模块
上面讲述了邮件的发送过程,接下来使用email模块来构建我们的邮件主体
构造一个邮件对象就是一个Message对象,要构造一个文本邮件对象,使用MIMEText;如果要构造一个图片作为邮件附件,使用MIMEImage,如要把多个对象组合起来,需要用到MIMEMultipart对象。MIMEBase对象可以表示任何对象。
email模块下面有mime包(多用途互联网邮件扩展),mime包下有三个模块:
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
1)使用MIMEText 构造普通文本邮件
MIMEText(strText, subType, encode)
strText:邮件正文,可以是普通str字符串,也可以是html字符串
subType:正文类型,有text/plain 和text/html 两种
encode:一般是utf-8,用于保证多语言的兼容性。
如:MIMEText("hello,python", 'plain', 'utf-8') # 发送普通文本信息
MIMEText("<html><body><p>hello,python<p></body></html>", 'html', 'utf-8')
2)添加附件:
a)发送文件作为附件(MIMEText)
from email.mime.text import MIMEText
sendfile = open(filepath, "rb").read()
text = MIMEText(sendfile, 'base64', 'utf-8')
text["Content-Type"] = "application/octet-stream" # octet-stream:以流的形式保存文件,如果具体的知道是什么类型的文件是可以直接用具体文件形式的,如"image/png"
text["Content-Disposition"] = 'attachment; filename="显示的名字"'
b)添加图片(MIMEImage)
from email.mime.image import MIMEImage
image = open(filepath,"rb")
imageData = image.read()
img = MIMEImage(imageData,'base64')
img.add_header("Content-ID","<image1>")
img["subject"] = "Test"
3、添加图片,html,文件,正文等
import smtplib
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
EMAIL_HOST = "smtp.qq.com" # 指定连接的邮箱smtp服务器地址
EMAIL_PORT = "25" # 指定连接服务器的端口
EMAIL_FROM = "xxxxxx@qq.com" # 发送邮箱地址
EMAIL_PASS = "yrtanyvnhfczbggi" # 发送邮箱密码(授权码)
RECEIVER = ["xxxxxx@xxx.com"] # 接收邮箱地址
SUBJECT = "测试" # 邮件主题
class SendMail():
def __init__(self, msg):
self.msg = msg
def sendText(self):
# 发送文字内容
text = "Hi! Nice to meet you! "
text_plain = MIMEText(text, 'plain', 'utf-8')
self.msg.attach(text_plain)
def sendImage(self):
# 将图片作为附件发送
img = open(path, "rb")
data = img.read()
image = MIMEImage(data)
image.add_header("Content-ID", "<image1>")
image.add_header("Content-Disposition", "attachment", filename='image.png')
self.msg.attach(image)
img.close()
def sendFile(self):
# 发送文件附件
f = open(filepath, "rb")
data = f.read()
file = MIMEText(data, 'base64', 'utf-8')
file.add_header("Content-Type", "application/octet-stream")
file.add_header("Content-Dispositon", "attachment", filename='file')
self.msg.attach(file)
f.close()
def sendHTML(self):
# 将html内容作为附件发送
html = """
<html>
<body>
<p>Hi, how are you</p>
</body>
</html>
"""
mime = MIMEText(html, "html", "utf-8")
mime.add_header("Content-Disposition", "attachment", filename="file.html")
self.msg.attach(mine)
def sendImageAsContent(self):
# 在内容中显示图片
img = open(imagepath, "rb")
image = MIMEImage(img.read())
image.add_header("Content-ID", "<0>")
image.add_header("Content-Disposition", "attachment", filename="image.png")
self.msg.attach(image)
self.msg.attach(MIMEText("<html><body><p><img src='cid:0'></p></body></html>", "html", "utf-8")) # cid:对应的Content-ID
img.close()
def sendMail(self):
server = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
server.login(EMAIL_FROM, EMAIL_PASSWORD)
server.sendmail(EMAIL_FROM, RECEIVER, self.msg.as_string())
print("end...")
if __name__ == "__main__":
msg = MIMEMultipart("mixed")
msg["From"] = EMAIL_FROM
msg["To"] = ";".join(RECEIVER)
msg["Subject"] = "测试邮件"
mail = SendMail(msg)
mail.sendText()
mail.sendImage()
mail.sendFile()
mail.sendHTML()
mail.sendImageAsContent()
mail.sendMail()