SMTP:
Simple Mail Transfer Protocol,即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。
python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。
1.Python发送 SMTP 简单示例如下:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import datetime
import logging
FORMAT = '%(asctime)s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
def get_today():
h=datetime.datetime.now()
today=h.strftime("%Y-%m-%d")
return today
class MailSend:
def __init__(self):
self.mail_host = "smtp.qq.com" #设置邮件服务器
self.mail_user="1xxxxxx@qq.com" #sftp账号(邮箱账号)
self.mail_pass="fobbaybdxxxxx" #密码
self.sender="1xxxxxxx@qq.com" #发件人
self.receivers=['1xxxxxxx@qq.com'] #收件人列表
def send(self,subject,content): #传参:邮件主题和邮件正文内容
message = MIMEText(content,'plain','utf-8') #邮件正文内容
message['From'] = Header('发件人','utf-8') #发件人昵称
message['To'] = Header('收件人','utf-8') #收件人昵称
message['Subject'] = Header(subject,'utf-8') #邮件主题
try:
server = smtplib.SMTP_SSL(self.mail_host,465) # 465为QQ邮箱ssl端口号
server.login(self.mail_user,self.mail_pass) #登录
server.sendmail(self.sender,self.receivers,message.as_string()) #发送邮件
server.quit()#关闭链接
logging.info("邮件发送成功")
except Exception as e:
logging.info("邮件发送失败,失败原因为:{}".format(e))
if __name__=="__main__":
mail_qq = MailSend()
subject="这是一封测试邮件"
today_data=get_today()
content="今天是 {} ,{}。".format(today_data,subject)
logging.info(content)
mail_qq.send(subject,content)
2.使用Python发送HTML格式的邮件
Python发送HTML格式的邮件与发送纯文本消息的邮件不同之处就是将MIMEText 中 _subtype 设置为html。示例如下:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import logging
FORMAT = '%(asctime)s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
class MailSend:
def __init__(self):
self.mail_host = "smtp.qq.com" #设置邮件服务器
self.mail_user="1xxxxxx@qq.com" #sftp账号(邮箱账号)
self.mail_pass="fobbaybdxxxxx" #密码
self.sender="1xxxxxxx@qq.com" #发件人
self.receivers=['1xxxxxxx@qq.com'] #收件人列表
def send(self,subject,content): #传参:邮件主题和邮件正文内容
message = MIMEText(content,'html','utf-8') #邮件正文内容
message['From'] = Header('发件人','utf-8') #发件人昵称
message['To'] = Header("收件人",'utf-8') #收件人昵称
message['Subject'] = Header(subject,'utf-8') #邮件主题
try:
server = smtplib.SMTP_SSL(self.mail_host,465) # 465为QQ邮箱ssl端口号
server.login(self.mail_user,self.mail_pass) #登录
server.sendmail(self.sender,self.receivers,message.as_string()) #发送邮件
server.quit()#关闭链接
logging.info("邮件发送成功")
except Exception as e:
logging.info("邮件发送失败,失败原因为:{}".format(e))
if __name__=="__main__":
mail_qq = MailSend()
subject="这是一封测试邮件"
content = """
<p>Python 邮件发送测试</p>
<p><a href="http://www.baidu.com">这是一个百度链接</a></p>
"""
logging.info(content)
mail_qq.send(subject,content)
3.使用python发送带附件的邮件
发送带附件的邮件,首先要创建 MIMEMultipart() 实例,然后构造附件,如果有多个附件,可依次构造,最后发送。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import logging
FORMAT = '%(asctime)s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
class MailSend:
def __init__(self):
self.mail_host = "smtp.qq.com" #设置邮件服务器
self.mail_user="1xxxxxx@qq.com" #sftp账号(邮箱账号)
self.mail_pass="fobbaybdxxxxx" #密码
self.sender="1xxxxxx@qq.com" #发件人
self.receivers=['1xxxxxx@qq.com'] #收件人列表
def addAttach(self,filename): #构造附件,filename为要发送的文件名
att = MIMEText(open(filename,'rb').read(),'base64','utf-8')
att['Content-Type'] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename={}'.format(filename.split('/')[-1]) #邮件中附件显示的文件名
return att
def send(self,subject,content,*args): #主题、内容、附件(可以有多个)
message = MIMEMultipart() #创建一个带附件的示例
message['From'] = Header('发件人','utf-8') #发件人昵称
message['To'] = Header("收件人",'utf-8') #收件人昵称
message['Subject'] = Header(subject,'utf-8') #邮件主题
message.attach(MIMEText(content,'plain','utf-8')) #邮件正文内容
#添加附件
for att in args:
message.attach(att)
try:
server = smtplib.SMTP_SSL(self.mail_host,465) # 465为QQ邮箱ssl端口号
server.login(self.mail_user,self.mail_pass) #登录
server.sendmail(self.sender,self.receivers,message.as_string()) #发送邮件
server.quit()#关闭链接
logging.info("邮件发送成功")
except Exception as e:
logging.info("邮件发送失败,失败原因为:{}".format(e))
if __name__=="__main__":
mail_qq = MailSend()
subject="这是一封测试邮件"
att1 = mail_qq.addAttach('a.txt') #附件1为 a.txt文件
att2 = mail_qq.addAttach('a.log') #附件2为 a.log文件
content = "这是一个附件邮件,详情见附件..."
logging.info(content)
mail_qq.send(subject,content,att1,att2) #发送两个附件